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

后端 未结 12 1352
伪装坚强ぢ
伪装坚强ぢ 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: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 
        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;   
        }
    

提交回复
热议问题