【发布时间】:2010-07-18 17:50:36
【问题描述】:
我目前正在通过 K.N. King 的C 编程:一种现代方法。我已经完成了第 8 章(数组)的正文,我很想继续阅读第 9 章,但是我还没有解决每章末尾的所谓“编程项目”。不幸的是,14 号……困扰我。
编写一个程序来反转句子中的单词。
Enter a sentence: you can cage a swallow can't you?
Reversal of sentence: you can't swallow a cage can you?
提示:使用循环逐个读取字符并将它们存储在一维char数组中。让循环在句点、问号或感叹号(“终止字符”)处停止,它们保存在单独的 char 变量中。然后使用第二个循环在数组中向后搜索最后一个单词的开头。打印最后一个单词,然后向后搜索倒数第二个单词。重复直到到达数组的开头。最后,打印结束符。
我一直在考虑将单词定义为空格之间的字符序列。因此,当到达一个空格时,向后退,打印每个字符,直到找到另一个空格。我的 first 版本的程序只打印了第一个单词。它的 current 版本只打印其他单词。我已经坚持了两天,所以任何帮助都非常感谢。这是我的代码以及输出示例。希望我已经正确记录了我的代码。提前致谢!
代码
/* Include the standard I/O library */
#include<stdio.h>
/* Define main */
int main(void) {
/**
* Declare an array of characters storing the sentence, as well as
* a character representing the current character under cursor and
* the terminating character
*/
char sentence[100] = { ' ' }, c, tc;
/**
* Declare a loop counter already initialized at 0, an incremental
* variable, as well as the size of the read sentence
*/
int i = 0, j = 1, size = 0;
/* Get the sentence */
printf("Enter a sentence: \n");
for(c = getchar(); (c != '.') && (c != '!') &&
(c != '?') && (c != '\n'); c = getchar(), i++) {
sentence[i] = c; /* Store the current character in the array */
size++; /* Increase the sentence's size */
}
tc = c; /* Get the terminating character */
/**
* Go backward through the array, printing each sequence of characters
* between spaces
*/
for(i = 99; i >= 0; i--) {
if(sentence[i] == ' ') {
while(sentence[i + j] != ' ') {
printf("%c", sentence[i + j]);
j++;
}
j = 1; /* Reset the incremental variable */
printf(" "); /* Print a tailing space */
}
}
/**
* Delete the tailing blank space and print the terminating character,
* as well as a new line
*/
printf("\b%c\n", tc);
return 0; /* Return 0 upon successful program execution */
}
输出:
【问题讨论】:
-
有一个更简单的解决方案,恕我直言。首先将每个单词反转到位,然后将整个字符串反转。
-
@Carl Norum 我的问题似乎与分隔单词有关。我将如何更容易地反转每个单词?谢谢!
-
我现在正在写一个简单的例子。稍等一下!