跟小D每日学口语

按单词反转字符串

按单词反转字符串

并不是简单的字符串反转,而是按给定字符串里的单词将字符串倒转过来,就是说字符串里面的单词还是保持原来的顺序,这里的每个单词用空格分开。例如:
Here is www.msjl.net
经过反转后变为:
www.msjl.net is Here
如果只是简单的将所有字符串翻转的话,可以遍历字符串,将第一个字符和最后一个交换,第二个和倒数第二个交换,依次循环。其实按照单词反转的话可以在第一遍遍历的基础上,再遍历一遍字符串,对每一个单词再反转一次。这样每个单词又恢复了原来的顺序。
  1. char* reverse_word(const char* str)
  2. {
  3.      int len = strlen(str);
  4.      char* restr = new char[len+1];
  5.      strcpy(restr,str);
  6.      int i,j;
  7.      for(i=0,j=len-1;i<j;i++,j--)
  8.      {
  9.           char temp=restr[i];
  10.           restr[i]=restr[j];
  11.           restr[j]=temp;
  12.      }
  13.      int k=0;
  14.      while(k<len)
  15.      {
  16.           i=j=k;
  17.           while(restr[j]!=' ' && restr[j]!='' )
  18.                j++;

  19.           k=j+1;
  20.           j--;
  21.           for(;i<j;i++,j--)
  22.           {
  23.                char temp=restr[i];
  24.                restr[i]=restr[j];
  25.                restr[j]=temp;
  26.           }
  27.      }
  28.      return restr;
  29. }
复制代码


如果考虑空间和时间的优化的话,当然可以将上面代码里两个字符串交换部分改为异或实现。
例如将
          char temp=restr;

          restr=restr[j];

          restr[j]=temp;

改为
          restr^=restr[j];

          restr[j]^=restr;

          restr^=restr[j];

 

 

 

        //"I am a student” => "student a am I"(只适合中间只有一个空格的情况,中间有多个空格的情况后续补上)
        static void ReverseWords(char[] sentence)
        {
            //先将整个句子反转,例如:“I am a student” => "tneduts a ma I"
            ReverseString(sentence, 0, sentence.Length-1);
            int startIndex = 0, endIndex = 0;
            int i = 0;
            while( i < sentence.Length)
            {
                if (sentence[i] == ' ')//Means the end of a word
                {
                    endIndex = i - 1;
                    ReverseString(sentence, startIndex, endIndex);
                    if (i + 1 < sentence.Length)
                    {
                        startIndex = i + 1;
                        endIndex = startIndex;
                    }
                }
                else
                {
                    endIndex++;
                }
                i++;

            }
           
        }

        //反转整个句子
        static void ReverseString(char[] str, int startIndex, int endIndex)
        {  
            int len = endIndex - startIndex + 1;
            char temp;
            for (int i = 0; i < len/2; i++)
            {
               
                temp = str[i + startIndex];
                str[i + startIndex] = str[startIndex + len - i - 1];
                str[startIndex + len - i - 1] = temp;
            }
        }

 

posted @ 2010-07-13 12:25  简简单单幸福  阅读(1809)  评论(0编辑  收藏  举报