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

后端 未结 12 1449
伪装坚强ぢ
伪装坚强ぢ 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 05:14

    My code,just traverse from the last and if you find a space print the characters before it,now change the end to space-1;This will print till the second word,finally just print the first word using a single for loop.Comment for alter approach.

    Program:

    #include
    int main()
    {
     char str[200];
    int i,j,k;
    scanf("%[^\n]s",&str);
    for(i=0;str[i]!='\0';i++);
    i=i-1;
    for(j=i;j>=0;j--)
    {
        if((str[j])==' ')
        {
            for(k=j+1;k<=i;k++)
            {
                printf("%c",str[k]);
            }
            i=j-1;
            printf(" ");
        }
    
    }
    for(k=0;k<=i;k++)
    {
        printf("%c",str[k]);
    }
    }
    

提交回复
热议问题