【问题标题】:Reverse a string word by word逐字反转字符串
【发布时间】:2013-03-13 16:21:40
【问题描述】:

我可以反转一个字符串。例如,我可以将“reverse a string”反转为“esrever a gnirts”。但是我不能像“string a reverse”这样逐字地反转它。

void reverseString(char string[],char *start, char* end)
{

    char tmp; //temporary variable to swap values
    int count = 0;
    while(start<end)
    {
        if(*start==' ')
        {
            printf("found space count %d \n",count);
            reverseString(string,start-count,start);
        }
        tmp = *start;
        *start = *end;
        *end = tmp;
        *start++;
        *end--;
        count++; 
    }

    printf(" string %s \n", string); 
}

int main()
{
    char string[] = "reverse a string word by word";
    char *start =string;
    char *end =start+ strlen(string) -1;
    reverseString(string,start,end);
    return 0;
}

【问题讨论】:

  • 这在现场很难。保持简单,只需创建一个新字符串,然后将每个单词附加到该字符串,然后用新值替换原始字符串。

标签: c string


【解决方案1】:

做你已经做过的事情,然后反转整个结果(不特别处理空格)。

【讨论】:

    【解决方案2】:

    就是这样。我能够逐字反转字符串以及整个字符串。只需浏览代码,看看逻辑是否有帮助。

    #include <stdio.h>
    #include <string.h>
    
    void stringrev(char *);
    void reverseWords(char *);
    void reverseString(char* , int);
    
    int main()
    {
    
        char string[] = "reverse a string word by word";
        reverseWords(string);
        printf("\nWord-Wise Reversed String : %s\n",string);
        stringrev(string);
        return 0;
    
    }
    
    void reverseWords(char * str)
    {
        int i = 0, j = 0;
        reverseString( str, strlen(str) ); 
        while( 1 ) // Loop forever
        {
            if( *(str+j) == ' ' || *(str+j) == '\0') // Found a word or reached the end of sentence
            {
                reverseString( str+i, j-i );
                i = j+1;
            }
            if( *(str+j) == '\0')
            {
                break;
            }
            j++;
        }
    }
    
    void reverseString(char* str, int len)
    {
        int i, j;
        char temp;
        i=j=temp=0;
    
        j=len-1;
        for (i=0; i<j; i++, j--)
        {
            temp=str[i];
            str[i]=str[j];
            str[j]=temp;
        }
    }
    
    void stringrev(char *str)
    {
        int i=-1,j=0;
        char rev[50];
    
        while(str[i++]!='\0');
    
            while(i>=0)
             rev[j++] = str[i--];
    
        rev[j]='\0';
    
        printf("\nComplete reverse of the string is : %s\n",rev);    
    }
    

    【讨论】:

    • 整洁...反转整个字符串,然后反转每个现在反转的单词。为我工作。 stringrev() 函数并不是真正需要解决问题的。
    【解决方案3】:

    对这个问题使用堆栈实现

    Step1:将字符串写入文件

    Step2:从文件中读取并推送到链表

    Step3:在这个链表上使用栈实现

    Step4:从头到尾弹出链表!!

    反面就是这样……!!

    【讨论】:

      【解决方案4】:

      使用 C# 反转字符串中的单词

      public  string ReverseWordsInString(string inputString)
      {
          string output = string.Empty;
          string[] splitStrings = inputString.Split(' ');
          for (int i = splitStrings.Length-1; i > -1 ; i--)
          {
              output = output + splitStrings[i]+ " ";
          }
          return output;
      }
      

      【讨论】:

      • C# 不是 C。这两种语言有完全不同的哲学。在 C 中没有 string + string 运算符,由于该运算符非常慢,因此避免使用。
      【解决方案5】:

      效率不高,但应该可以:

      void reverse_string_word(char *data)
      {
          char *saveptr;
          char *word;
          char *tmp = malloc(strlen(data) + 1);
          char *tmp2 = malloc(strlen(data) + 1); 
      
          *tmp = 0;
          *tmp2 = 0;
      
          word = strtok_r(data, " ", &saveptr);
          if (word)
          {
              strcpy(tmp, word);
          }
          while (word)
          {
             word = strtok_r(NULL, " ", &saveptr);
             if (word)
             {
                sprintf(tmp2, "%s %s", word, tmp);
                strcpy(tmp, tmp2);
             }
          }
          strcpy(data, tmp);
          free(tmp);
          free(tmp2);
      }
      

      【讨论】:

        【解决方案6】:

        将其拆分为一个单词数组( char** ),将其反转,然后再次连接。

        【讨论】:

          【解决方案7】:

          这是一个不使用 Scanner 或 Stack 来解析单词的 Java 解决方案。从字符串的末尾开始并向后工作。可能更优雅但有效 - 如果有人有递归 java 解决方案,我想看看。

          "one two three four" is returned as "four three two one" 
          
          private void reverseWordsNoStackNoScanner(String str) {
                  System.out.println("reverseWordsNoStackNoScanner "+str);
          
                  String[] buff = new String[str.length()];
                  int end=str.length()-1;
                  int j=end;
                  int start=0;
                  int ptr=0;
                  for (int i=str.length()-1;i>=0;i--){
                      boolean writeBuff=false;
                      if (str.charAt(i)!=' ') { // have we backed up to a blank?
                          j--; //no
                      } else { //yes! write out this word
                          writeBuff=true;
                      }
                      if (i==0) writeBuff=true; //are we done (position 0)?
          
                      if (writeBuff) { //time to write a word?                
                          //we've hit a delimiter (or we're done)     
                          ptr=j;  //pointing at a blank or the beginning
                          ptr++;  //bump past the blank or the beginning
                          while(ptr<=end){ //write the word from beginning to finish
                              buff[start++]=String.valueOf(str.charAt(ptr++));
                          }
                          //don't write a blank when we are on the last word (past the end)
                          if (i>0)buff[start++]=" "; 
                          j--;
                          //set pointers for next iteration
                          end=j; //back up end ptr to new 'end' - to parse the next word
                      } 
                  }
                      //print out our reversed word string
                  for (String s: buff) {
                      System.out.print(s);                        
                  }
              }
          

          【讨论】:

            【解决方案8】:

            从头开始读取字符串并将每个字符压入字符堆栈。一旦遇到空格或换行符或 eof,就开始弹出字符并在标准输出上一一打印,或根据需要将其存储在文件中。

            【讨论】:

              【解决方案9】:
              'My name is' return as 'yM eman si'
                   'My name is' return as 'yM      eman si'
               #include<stdio.h>
               #include<malloc.h>
               #include<string.h>
               void reve(char [],int,int);
               void main()
               {
                 char *a;
                 int i,j=-1;
                 a=(char*)malloc(1000*sizeof(char));
                 gets(a);
                 for(i=0;a[i]!='\0';i++)
                 {
                    if(a[i]!=' '&&j==-1)
                     j=i;
                    if((a[i]==' '&&a[i+1]!=' '&&j>=0)||a[i+1]=='\0')
                    {
                      a[i]==' '?reve(a,j,i-1):reve(a,j,i);
                      j=-1;                
                    }
               } 
                 for(i=0;a[i]!='\0';i++)
                 printf("%c",a[i]); 
              

              }

              void reve(char a[],int j,int i)
              {
                 char temp;
                 if(a[0]==' ')
                 j=0;
                for(;i!=j&&j<i;i--,j++)
                {
                    temp=a[j];
                    a[j]=a[i];
                    a[i]=temp;
                 }
              

              }

              【讨论】:

                【解决方案10】:
                'i love india' return as  'india love i'
                '     i love india' return as 'india love      i'
                #include<stdio.h>
                #include<malloc.h>
                #include<string.h>
                void reve(char [],int,int);
                void main()
                {
                  char *a;
                  int i,j=-1;
                  a=(char*)malloc(1000*sizeof(char));
                  gets(a);
                  for(i=0;a[i]!='\0';i++)
                  {
                    if(a[i]!=' '&&j==-1)
                     j=i;
                     if((a[i]==' '&&a[i+1]!=' '&&j>=0)||a[i+1]=='\0')
                     {
                        a[i]==' '?reve(a,j,i-1):reve(a,j,i);
                        j=-1;                
                      }
                 } 
                  reve(a,0,i-1);
                  for(i=0;a[i]!='\0';i++)
                  printf("%c",a[i]); 
                

                }

                void reve(char a[],int j,int i)
                {
                  char temp;
                  if(a[0]==' ')
                  j=0;
                 for(;i!=j&&j<i;i--,j++)
                 {
                     temp=a[j];
                      a[j]=a[i];
                      a[i]=temp;
                  }
                

                }

                【讨论】:

                • 感谢您的贡献。可以添加对您的方法和算法的一些解释。
                【解决方案11】:

                它不应该像其他人发布的那样复杂,请参考并提供反馈,很高兴改进它。

                #include <stdio.h>
                #include <string.h>
                
                
                void printWordsInReverse(char str[])
                {
                    int i;
                    int length = strlen(str);
                
                    for(i=length-1; i>=0; i--)
                    {
                        if(str[i] == ' ')
                        {
                            /* replace the space with null for the next word */
                            str[i] = '\0';
                            /* remove the white spaces */
                            if(str[i+1] != '\0')
                            {
                            /* print a word till the null character */
                                printf("%s ", &str[i+1]);
                            }
                        }
                    }
                    /* print the last word */
                    printf("%s", str);
                }
                
                int main()
                {
                    char str[] = "reverse a string";
                    printWordsInReverse(str);
                    return 0;
                }
                

                输出 : "string a reverse"

                【讨论】:

                  猜你喜欢
                  • 2016-03-03
                  • 2020-12-29
                  • 1970-01-01
                  • 1970-01-01
                  • 2016-01-06
                  • 1970-01-01
                  • 2013-01-13
                  相关资源
                  最近更新 更多