characters in a String Question
Hi !
I'm looking for the right code that takes a string and display the number of times each character displays in it. let's say.
string = "ttiokk"; the output should be :
t-----------2
i-----------1
o----------1
k----------2
I'm trying everything but it's not working. Your help is highly appreciated.
Thanks.
Re: characters in a String Question
For "ttooot", do you expect the output to be:
t --- 2
o --- 3
t --- 1
or:
t --- 3
o --- 3
?
Re: characters in a String Question
Yeah the second one t----3, o-----3 . any help is greatly appreciated ! thanks
Re: characters in a String Question
Quote:
Originally Posted by
xcreator
I'm looking for the right code that takes a string and display the number of times each character displays in it. let's say.
string = "ttiokk"; the output should be :
t-----------2
i-----------1
o----------1
k----------2
Check this:
Code:
var counter = new Dictionary<char, int>();
var str = "ttiokk";
for (int i = 0; i < str.Length; ++i) {
char iChar = str[i];
if (counter.ContainsKey(iChar)) {
counter[iChar] += 1;
} else {
counter.Add(iChar, 1);
}
}
var sb = new System.Text.StringBuilder();
var eChars = counter.GetEnumerator();
while (eChars.MoveNext()) {
sb.AppendFormat("{0} --- {1}\n", eChars.Current.Key, eChars.Current.Value);
}
MessageBox.Show(sb.ToString());
Re: characters in a String Question
Code:
string str = "tttttooooooott";
int[] characters = new int[256];
/*
for(int i=0;i<characters.Length;i++)
characters[i] = 0;
*/
for(int i=0;i<str.Length;i++)
characters[(int)str[i]]++;
for(int i=0;i<characters.Length;i++)
{
if(character[i] > 0)
Console.WriteLine("{0} --- {1}", (char)characters[i], characters[i]);
}
Re: characters in a String Question
Quote:
Originally Posted by
Talikag
Code:
string str = "tttttooooooott";
int[] characters = new int[256];
/*
for(int i=0;i<characters.Length;i++)
characters[i] = 0;
*/
for(int i=0;i<str.Length;i++)
characters[(int)str[i]]++;
for(int i=0;i<characters.Length;i++)
{
if(character[i] > 0)
Console.WriteLine("{0} --- {1}", (char)characters[i], characters[i]);
}
This doesn't work properly for weird unicode characters (like ones my country uses :)).
Re: characters in a String Question
Quote:
Originally Posted by
jmedved
This doesn't work properly for weird unicode characters (like ones my country uses :)).
right. this can be solved by increasing 256 to 2^16 (when ^ stands for pow). However, if you have 2^16 different characters, it will be smarter to use a Dictionary, as you did in your code.
Re: characters in a String Question
Quote:
Originally Posted by
Talikag
However, if you have 2^16 different characters
Actually there is 2^21 different characters in unicode. Those unicode guys overdid it a little.
Re: characters in a String Question
The real taste in doing these types of question comes when we code them in C language. (not C++)