【发布时间】:2018-12-10 17:10:01
【问题描述】:
我做了这个程序来反转给定字符串中单词的顺序。 (而且有效)
即输出:sentence first the is This
但是,在向数组中添加另一个句子时,我被卡住了。
例如,我需要有一个数组 {"This is the first sentence", "And this is the second"} 产生作为输出:sentence first the is This , second the is this And
int main() {
char str[] = {"This is the first sentence"};
int length = strlen(str);
// Traverse string from end
int i;
for (i = length - 1; i >= 0; i--) {
if (str[i] == ' ') {
// putting the NULL character at the position of space characters for
next iteration.
str[i] = '\0';
// Start from next character
printf("%s ", &(str[i]) + 1);
}
}
// printing the last word
printf("%s", str);
return 0;
}
我是 C 的新手,所以即使解决方案很简单,我也会被卡住也就不足为奇了。任何帮助,将不胜感激!谢谢!
【问题讨论】:
-
用二维数组试试。
-
这里可能重复检查答案stackoverflow.com/questions/48871795/…
-
SO 的 C-tag 中处理最多的问题(之一)怎么可能仍然是这样的问题? ;>
-
公平地说,这里的问题是不是如何反转字符串或数组,甚至不是如何反转句子中的单词——OP已经解决了问题!