how to perform reversing a sentence Word by Word in C?

后端 未结 12 1347
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 04:49
#include 

int main(void)
{
  int i,j;
  int wordstart = -1;
  int wordend = -1;
  char words[]= \"this is a test\";
  char temp;

  // Reverse each word
         


        
相关标签:
12条回答
  • 2021-01-25 04:49

    I would use write function similar to strrchr for finding last occurence of ' ', if its found print word that follows, rewrite this ' ' with '\0' and repeat it in loop till no more words are found. At the end I would print the content of this string again because there is most likely no ' ' before the first word.

    I would write own function instead of strrchr because strrchr calculates the lenght of the given string, which is redundant in this case. This length doesn't have to be calculated more than once.

    Here's the code:

    char* findLastWord(char* str, int* len)
    {
        int i;
        for (i = *len - 1; i >= 0; --i)
        {
            if (str[i] == ' ')
            {
                str[i] = '\0';
                if (i < *len - 1)
                {
                    *len = i - 1;
                    return &str[i + 1];
                }
            }
        }
        return NULL;
    }
    
    int main (int argc, char *argv[])
    {
        char str[] = " one two three  four five six ";
        int len = strlen(str);
    
        char* lastWord = findLastWord(str, &len);
        while (lastWord != NULL)
        {
            printf("%s\n", lastWord);
            lastWord = findLastWord(str, &len);
        }
        if (len > 1)
            printf("%s\n", str);
        return 0;
    }
    

    output:

    six
    five
    four
    three
    two
    one
    

    Hope this helps ;)

    0 讨论(0)
  • 2021-01-25 04:49
    #include<stdio.h>
    #include<string.h>
    
    void reverse(char *str, size_t len)
    {
        char tmp;
        size_t beg, end;
        if (len <=1) return;
    
        for (beg=0,end=len; beg < --end ; beg++) {
            tmp = str[beg];
            str[beg] = str[end];
            str[end] = tmp;
        }
    }
    
    int main(void)
    {
        char sentence[] = "one two three four five";
        size_t pos, len;
    
        printf("Before:%s\n",sentence);
        for (pos = len= 0;  sentence[pos]; pos += len) {
            pos += strspn( sentence+pos, " \t\n" );
            len = strcspn( sentence+pos, " \t\n" );
            reverse ( sentence + pos, len );
            }
        reverse ( sentence , pos );
    
        printf("After:%s\n",sentence);
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-25 04:51
    using stack 
    
    #include <iostream>  
    #include <stdio.h>
    #include <stack>
    
    int main()
    { 
    
        std::stack<string> st;
        char *words= "this is a test";
        char * temp =   (char *)calloc(1, sizeof(*temp));
        int size1= strlen(words);
        int k2=0;
        int k3=0;
        for(int i=0;i<=size1;i++)
        {
           temp[k2] = words[i];
           k2++;
            if(words[i] == ' ')     
            {  
                k3++;
                if(k3==1)
                    temp[k2-1]='\0';
    
                temp[k2]='\0';
                st.push(temp);
                k2=0;           
            }
            if(words[i] == '\0')
            {
                temp[k2]='\0';
                st.push(temp);
                k2=0;
                break;
            }               
        }
    
      while (!st.empty())
      {
           printf("%s",st.top().c_str());
            st.pop();
      }
    
    0 讨论(0)
  • 2021-01-25 04:57

    Perhaps this belongs on the code review site instead?

    Your approach seems very efficient to me (except that I would only call strlen(words) once and save the result in a register).

    Two possible bugs look like:

    wordend = strlen(words);
    

    should be

    wordend = strlen(words)-1;
    

    and

    for(j = wordstart ; j <= (wordend - wordstart) / 2 ; ++j) {
    

    should be

    for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
    

    Final code looks like (with some extra {}):

        #include <stdio.h>
        int main(int argc,char *argv[])
        {
            int i,j;
            char words[]= "this is a test";
            int L=strlen(words);
    
            // Reverse each word
            for(i = 0; i < L; ++i) {
              int wordstart = -1;
              int wordend = -1;
              if(words[i] != ' ') 
              {
                wordstart = i;
    
                for(j = wordstart; j < L; ++j) {
                  if(words[j] == ' ') {
                    wordend = j - 1;
                    break;
                  }
                }
                if(wordend == -1)
                  wordend = L-1;
                for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
                  char temp = words[j];
                  words[j] = words[wordend - (j - wordstart)];
                  words[wordend - (j - wordstart)] = temp;
                }
                i = wordend;
              }
            }
            printf("reversed string is %s:",words);
            return 0;   
        }
    
    0 讨论(0)
  • 2021-01-25 05:00
    if(words[i] != ' ') 
        wordstart = i;
    

    This statement what about the else part? if words[i] == ' ', and wordstart remains -1. So maybe try to use:

    while (words[i] && words[i] == ' ') ++i;
      if (!words[i])
          break;
    wordstart = i;
    

    Then you should output the result out of the i loop. Finally, if you want to get the result you expected, you should reverse the whole sentence once more, with the way you used in the loop.

    0 讨论(0)
  • 2021-01-25 05:02

    Simply we can just use a n*1 2D character array tailored to suit our needs!!!

    #include <stdlib.h>
    
    int main()
    {
        char s[20][20];
        int i=0, length=-1;
        for(i=0;;i++)
        {
            scanf("%s",s[i]);
            length++;
            if(getchar()=='\n')
                break;
        }
        for(i=length;i>=0;i--)
            printf("%s ",s[i]);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题