Created
September 18, 2014 00:32
-
-
Save ronnieoverby/3b03e9f85871c28e30fd to your computer and use it in GitHub Desktop.
Ways to count the occurrences of character 'g' in the string "debugging"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////////////////////////////////////// | |
// 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