句子反转功能

时间:2015-04-24 08:39:22

标签: c string

包括stdio.h

包括stdlib.h

包括string.h

#include <conio.h>

#define SIZE 40

int main( void )
{
    char str[ SIZE ];
    char strrev[ SIZE ];
    char *temp1;
    char *temp2;
    int turn = 0;

    printf( "Enter line of text: " );
    fgets( str, SIZE - 1, stdin );

    temp1 = strtok( str, " " );
    temp2 = strtok( NULL, " " );
    strcat( strrev, temp2 );
    strcat( strrev, temp1 );

问题在于内部条件:

    while( temp1 != NULL && temp2 != NULL ){
           if( turn == 0 ){
               temp1 = strtok( NULL, " " );
               strcat( strrev, temp1 );
               strcat( strrev, temp2 );
               turn = 1;

               }//end if
           else{
                temp2 = strtok( NULL, " " );
                strcat( strrev,temp2 );
                strcat( strrev, temp1 );
                turn = 0;

                }//end else

           }//end while

    printf( "\nThe reversed sentence is: %s", strrev );

    getche();
    return 0;
}//end function main

由于最终字符串temp1temp2中的任何一个将获得NULL,为什么循环功能不正确?

3 个答案:

答案 0 :(得分:1)

您可以使用递归来反转句子,使用sscanf来分割字符串:

#include <stdio.h>

void recursive(const char *s)
{
  char b[100];
  int n;

  if (sscanf(s, "%99s%n", b, &n) == 1)
    recursive(s + n), printf(" %s", b);
}

int main()
{
  recursive("foo bar baz");
  return 0;
}

答案 1 :(得分:1)

我不会使用strtok因为1)它会破坏原始字符串,你不能将它用于字符串文字; 2)字符串中单词之间的空格数将被破坏。

我会使用以下方法

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) 
{
    char *s = "This is a dog";
    size_t n = strlen( s );
    char t[n + 1];

    char *p = t;
    char *q = s + n;

    while ( q != s )
    {
        while ( q != s && isblank( *( q - 1 ) ) ) *p++ = *--q;
        char *tmp = q;
        while ( tmp != s && !isblank( *( tmp - 1 ) ) ) --tmp;
        memcpy( p, tmp, q - tmp );
        p += q - tmp;
        q = tmp;
    }

    *p = '\0';

    puts( s );
    puts( t );

    return 0;
}

程序输出

This is a dog
dog a is This

答案 2 :(得分:0)

感谢您的帮助,我想解决这个问题:

#include <stdio.h>
#include <string.h>
#include <conio.h>
#define SIZE 40

void reverse( char sentence[], char *token2 );

int main( void )
{
    char sentence[ SIZE ] = "This is a dog";
    char *token1;
    char *token2;
    token1 = strtok( sentence, " " );
    reverse( sentence, token2 );
    printf( "%s", token1 );

    getche();
    return 0;
}//end function main

void reverse( char sentence[], char *token2 )
{

     if( token2 == NULL )
         return;

     else{
          token2 = strtok( NULL, " " );
          reverse( sentence, token2 );

          if( token2 != NULL ){ 
              printf( "%s ", token2 );

              }//end if    

         }//end else

}//end function reverse