一个字符串,返回字符串中每一个单词跟它的个数。

Posted on 2011-08-03 09:00  flydreamer  阅读(478)  评论(0)    收藏  举报

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]))

                    {

                        m[i]++; //counter

                        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);

       

        }

写的好复杂,而且有点乱。。

 

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3