Snippet
/// <summary>
/// Counts the number of times a character appears in a string.
/// </summary>
private string countchars(string str)
{
string[,] alphanumerics = { { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" } };
string result = "";
int FI = 0;
int LI = 0;
int counts = 0;
for (int i = 0; i < 35; i++)
{
//Get the lower-case characters first//
FI = str.IndexOf(alphanumerics[0, i]);
while (FI > -1)
{
counts++;
LI = FI + 1;
FI = str.IndexOf(alphanumerics[0, i], LI);
}
if (counts > 0)
{
result += "There are " + counts + " " + alphanumerics[0, i] + "'s.\n";
}
//Count upper-case characters//
FI = str.IndexOf(alphanumerics[0, i].ToUpper());
while (FI > -1)
{
counts++;
LI = FI + 1;
FI = str.IndexOf(alphanumerics[0, i].ToUpper(), LI);
}
if (counts > 0)
{
result += "There are " + counts + " " + alphanumerics[0, i].ToUpper() + "'s.\n";
}
counts = 0;
}
return result;
}
//Example usage:
//(After creating a textbox, named textBox1):
MessageBox.Show(countchars(textBox1.Text));
Copy & Paste
|