请问如何将字符数组倒叙并忽略标点符号?
比如以下实例
首先,提示用户用英语输入一句话(假设用户输入的单词数小于15,每个单词长度小于15,并且句子结尾有标点符号);
然后,解析用户输入内容中的所有单词(无需保留标点符号),并将其逆序存放到数组result中,每个单词间用空格分隔;
最后,输出result的内容。
例如:如果用户输入:“How are you?”,则系统输出:“you are How”。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void reverse(char s[][15], int n)
{
for (int i = 0; i < n / 2; i++)
{
char temp[15];
strcpy(temp, s[i]);
strcpy(s[i], s[n - 1 - i]);
strcpy(s[n - 1 - i], temp);
}
}
int main()
{
char sentence[200], word[15], result[15][15];
int i = 0, j = 0, k = 0;
printf("Please enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
while (sentence[i] != '\0')
{
if (isalpha(sentence[i])) // 判断该字符是否为字母
{
word[j++] = tolower(sentence[i]); // 将字母转换为小写并存储到数组word中
}
else if (j > 0) // 如果该字符是标点符号,并且数组word中已经存储了字母
{
word[j] = '\0'; // 在word中添加字符串结束符
strcpy(result[k++], word); // 将单词存储到数组result中,并将k加1
j = 0; // 重置j
}
i++; // 处理下一个字符
}
if (j > 0)
{
word[j] = '\0'; // 处理最后一个单词
strcpy(result[k++], word);
}
reverse(result, k);
for (i = 0; i < k; i++)
{
printf("%s ", result[i]);
}
printf("\n");
return 0;
}