Skip to content

Instantly share code, notes, and snippets.

@ronnieoverby
Created September 18, 2014 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronnieoverby/3b03e9f85871c28e30fd to your computer and use it in GitHub Desktop.
Save ronnieoverby/3b03e9f85871c28e30fd to your computer and use it in GitHub Desktop.
Ways to count the occurrences of character 'g' in the string "debugging"
///////////////////////////////////////////
// Method #1
// Uses a for loop and substring
///////////////////////////////////////////
int letterCount = 0;
string strText = "Debugging";
string letter;
for (int i = 0; i < strText.Length; i++)
{
letter = strText.Substring(i,1);
if (letter == "g")
{
letterCount++;
}
}
string message = "g appears " + letterCount + " times";
///////////////////////////////////////////
// Method #2
// Uses a for loop and character index
///////////////////////////////////////////
int letterCount = 0;
string strText = "Debugging";
char letter;
for (int i = 0; i < strText.Length; i++)
{
letter = strText[i];
if (letter == 'g')
{
letterCount++;
}
}
string message = "g appears " + letterCount + " times";
///////////////////////////////////////////
// Method #3
// Uses a foreach loop
///////////////////////////////////////////
int letterCount = 0;
string strText = "Debugging";
foreach (char letter in strText)
{
if (letter == 'g')
{
letterCount++;
}
}
string message = "g appears " + letterCount + " times";
///////////////////////////////////////////
// Method #4
// Uses the count extension method and
// a lambda expression
///////////////////////////////////////////
int count = "Debugging".Count(c => c == 'g');
string message = "g appears " + count + " times";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment