reversing only certain words of a string

后端 未结 1 1295
一向
一向 2021-01-28 05:16

I have a string with the name \"Mustang Sally Bob\" After i run my code i want the string output to be like this: gnatsuM yllaS boB My approach is to count the word

1条回答
  •  深忆病人
    2021-01-28 05:50

    In general the approach is incorrect.

    For example an arbitrary string can start with blanks. In this case the leading blanks will not be outputted.

    The last word is ignored if after it there is no blank.

    The variable words does not keep the position where a word starts.

    Calculating the length of a string with this loop

    for(length=0;test[length] !=0&&test[length];length++);
    

    that can be written simpler like

    for ( length = 0; test[length] != '\0' ; length++ );
    

    is redundant. You always can rely on the fact that strings are terminated by the zero-terminating character '\0'.

    I can suggest the following solution

    #include 
    
    int main( void )
    {
        const char *test = "Mustang Sally Bob";
    
        for ( size_t i = 0; test[i] != '\0'; )
        {
            while ( test[i] == ' ' ) putchar( test[i++] );
    
            size_t j = i;
    
            while ( test[i] != '\0' && test[i] != ' ' ) i++;
    
            for ( size_t k = i; k != j; ) putchar( test[--k] );
        }
    
        return 0;
    }
    

    The program output is

    gnatsuM yllaS boB
    

    You could append the program with a check of the tab character '\t' if you like. In C there is the standard C function isblank that performs such a check.

    Here is a demonstrative program that uses the function isblank. I also changed the original string literal.

    #include 
    #include 
    
    int main( void )
    {
        const char *test = " Mustang\tSally\tBob ";
    
        puts( test );
    
        for ( size_t i = 0; test[i] != '\0'; )
        {
            while ( isblank( ( unsigned char )test[i] ) ) putchar( test[i++] );
    
            size_t j = i;
    
            while ( test[i] != '\0' && !isblank( ( unsigned char)test[i] ) ) i++;
    
            for ( size_t k = i; k != j; ) putchar( test[--k] );
        }
    
        putchar( '\n' );
    
        return 0;
    }
    

    The program output is

     Mustang    Sally   Bob 
     gnatsuM    yllaS   boB
    

    0 讨论(0)
提交回复
热议问题