1.比如输入:I love you,I love all of you!!
返回: I 2
love 2
you 2
all 1
of 1
Solution:
public class MyClass
{
public static void WordCounter(string str)
{
char [] n=str .ToCharArray();
List<string > sb = new List<string>();
int j=0;
for (int i = 0; i < str.Length; i++)
{
if (!Char.IsLetter(n[i])) //判断是否为字母?
{
string str1=new string (n,j,i-j);
sb.Add(str1);
j = i+1;
//防止出现连续两个字符都不是字母的情况,如I love you ,,,I love all of you.
if(i+1<str.Length)
while(!Char.IsLetter(n[i+1]))
{
i++;
j++;
}
}
}
int [] m=new int[sb.Count ];
for (int i = 0; i < sb.Count ; i++)
{
m[i] = 1;
//取出对比并计数
for (int l = i+1; l <sb.Count ; l++)
{
if (sb[i].Equals(sb[l]))
{
sb.RemoveAt(l);
}
}
}
for (int i = 0; i < sb.Count;i++ )
{
Console.WriteLine("{0} {1}", sb[i].ToString(), m[i].ToString());
}
}
public static void Main()
{
string str = "I love you,I love all of you!";
WordCounter(str);
}
写的好复杂,而且有点乱。。
浙公网安备 33010602011771号