在C中反转字符串

我尝试构建将反转字符串的代码,如下所示:

input: Hello World! output:olleH !dlroW 

我不能使用任何指针我构建的代码是,有一个函数,得到句子列表地址(矩阵与多达20行) – 表,表中的句子数和句子的数量我想改变。

 int changeCharOrder(char table[][MAX_SENTENCE_LENGTH], int numOfSentences, int sentenceToChange) { int slen, slen2, slenrev, lastwordlen=0, c=0, i, q, f, start=0; char reversed[MAX_SENTENCE_LENGTH]; // the reversed sentence will be here char oneword[MAX_SENTENCE_LENGTH]; // i tried to split the sentence to words and then reverse them reversed[0] = '\0'; slen = strlen(table[sentenceToChange]); for (i = 0; i  i; q--){ // here is the reversing code. it's not working well reversed[q-1] = table[sentenceToChange][start]; start++; } start++; lastwordlen = strlen(oneword); reversed[slen] = '\0'; c = 0; } reversed[slen] = '\0'; printf("%s",reversed); } 

它没有按预期工作。 我只能反转第一个单词。 任何建议? 谢谢

试试这个

 for (i=0; i=0;c--){ //you can remove `q=c` also 'for(;c>=0;c--)' will also work reversed[start]=oneword[c]; start++; } reversed[start++]=' '; reversed[start]='\0'; c=0; } printf("\n%s",reversed); 
 #include  int main( void ){ char sentence[] = "Hello World!"; int i, word_top, word_end; for(i=0; sentence[i]; ++i){ if(sentence[i] == ' ') continue; word_end = word_top = i; while(sentence[word_end] && sentence[word_end] != ' ') ++word_end; i = --word_end;//move back one while(word_end > word_top){ //swap top and end char temp = sentence[word_top]; sentence[word_top++] = sentence[word_end]; sentence[word_end--] = temp; } } puts(sentence); return 0; } 

这是另一个类似的情况

 #include  #include  #define MAX_SENTENCE_LENGTH 30 int changeCharOrder(char table[][MAX_SENTENCE_LENGTH], int sentenceToChange) { int i=0, j, k; char *sptr = table[sentenceToChange]; // make code more readable char reversed[MAX_SENTENCE_LENGTH]; // reversed words will be here strcpy (reversed, sptr); // copy source spaces and terminator while (sptr[i]) { // until end of string while (sptr[i] > 0 && sptr[i] <= ' ') // find first char i++; j = i; while (sptr[j] > ' ') // find end of word j++; k = j; // where word ended while (i < j) // reverse the word reversed[i++] = sptr [--k]; } printf("%s\n%s\n\n", sptr, reversed); } int main(void) { char sents [3][MAX_SENTENCE_LENGTH] = {"Hello World!", "Second sentence", " Three words here ."}; changeCharOrder (sents, 0); changeCharOrder (sents, 1); changeCharOrder (sents, 2); return 0; } 

节目输出:

 Hello World! olleH !dlroW Second sentence dnoceS ecnetnes Three words here . eerhT sdrow ereh .