gpt4 book ai didi

c - 在句子中颠倒单词

转载 作者:太空狗 更新时间:2023-10-29 17:18:46 24 4
gpt4 key购买 nike

我目前正在通过 K.N. King 的 C 编程:一种现代方法。我已经完成了第 8 章(数组)的课文,我迫不及待地想继续学习第 9 章,但我还没有解决每章末尾所谓的“编程项目”。不幸的是,第 14 号......让我烦恼

Write a program that reverses the words in a sentence.

Enter a sentence: you can cage a swallow can't you?
Reversal of sentence: you can't swallow a cage can you?

Hint: Use a loop to read the characters one by one and store them in a one-dimensional char array. Have the loop stop at a period, question mark, or exclamation point (the "terminating character "), which is saved in a separate char variable. Then use a second loop to search backward through the array for the beginning of the last word. Print the last word, then search backward for the next-to-last word. Repeat until the beginning of the array is reached. Finally, print the terminating character.

我一直在考虑将单词定义为空格之间的一系列字符。因此,当到达一个空格时,向后打印每个字符,直到找到另一个空格。我的程序的第一个 版本只打印了第一个词。它的当前 版本只打印其他单词。我已经坚持了两天,所以非常感谢任何帮助。这是我的代码,以及一个输出示例。希望我已经正确记录了我的代码。提前致谢!

代码

/* 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 */
}

输出:

http://drp.ly/1nYt5J

最佳答案

将每个单词压入堆栈并从索引 0 到 N-1 读取堆栈

关于c - 在句子中颠倒单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3276582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com