我试图在不改变单词顺序的情况下反转句子,
例如:“ Hello World” =>“ olleH dlroW”
这是我的代码:
#include <stdio.h>
#include <string.h>
char * reverseWords(const char *text);
char * reverseWord(char *word);
int main () {
char *text = "Hello World";
char *result = reverseWords(text);
char *expected_result = "olleH dlroW";
printf("%s == %s\n",result,expected_result);
printf("%d\n",strcmp(result,expected_result));
return 0;
}
char *
reverseWords (const char *text) {
// This function takes a string and reverses it words.
int i,j;
size_t len = strlen(text);
size_t text_size = len * sizeof(char);
// output containst the output or the result
char *output;
// temp_word is a temporary variable,// it contains each word and it will be
// empty after each space.
char *temp_word;
// temp_char is a temporary variable,// it contains the current character
// within the for loop below.
char temp_char;
// allocating memory for output.
output = (char *) malloc (text_size + 1);
for(i = 0; i < len; i++) {
// if the text[i] is space,just append it
if (text[i] == ' ') {
output[i] = ' ';
}
// if the text[i] is NULL,just get out of the loop
if (text[i] == '\0') {
break;
}
// allocate memory for the temp_word
temp_word = (char *) malloc (text_size + 1);
// set j to 0,so we can iterate only on the word
j = 0;
// while text[i + j] is not space or NULL,continue the loop
while((text[i + j] != ' ') && (text[i + j] != '\0')) {
// assign and cast test[i+j] to temp_char as a character,// (it reads it as string by default)
temp_char = (char) text[i+j];
// concat temp_char to the temp_word
strcat(temp_word,&temp_char); // <= PROBLEM
// add one to j
j++;
}
// after the loop,concat the reversed version
// of the word to the output
strcat(output,reverseWord(temp_word));
// if text[i+j] is space,concat space to the output
if (text[i+j] == ' ')
strcat(output," ");
// free the memory allocated for the temp_word
free(temp_word);
// add j to i,so u can skip
// the character that already read.
i += j;
}
return output;
}
char *
reverseWord (char *word) {
int i,j;
size_t len = strlen(word);
char *output;
output = (char *) malloc (len + 1);
j = 0;
for(i = (len - 1); i >= 0; i--) {
output[j++] = word[i];
}
return output;
}
问题是我用<= PROBLEM
标记的行,在第一个单词(在这种情况下为“ Hello”)上,一切正常。
在第二个单词(在本例中为“世界”)上,它向temp_word
添加了垃圾字符,
我用gdb
进行了检查,temp_char
不包含垃圾,但是运行strcat
时,附加在temp_word
上的最新字符将类似于{{1} }
它将W\006
附加到第二个单词内的所有字符,
我在终端上看到的输出很好,但是打印\006
并将strcmp
与result
进行比较,则会返回expected_result
。
- 可能是什么问题?
-
-94
字符是什么? - 为什么
\006
添加它? - 如何防止这种行为?