#include <stdio.h>
#include <string.h>
#include <ctype.h>
// 函数声明
void reverseWords(char *str);
int countWords(char *str);
int main() {
char article[1000];
printf("请输入英文文章: ");
fgets(article, sizeof(article), stdin);
// 去除fgets读取的换行符
article[strcspn(article, "\n")] = '\0';
int wordCount = countWords(article);
printf("单词数量: %d\n", wordCount);
reverseWords(article);
printf("逆序排列后的文章: %s\n", article);
return 0;
}
// 统计单词数量
int countWords(char *str) {
int count = 0;
int inWord = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isalnum(str[i])) {
if (!inWord) {
count++;
inWord = 1;
}
} else {
inWord = 0;
}
}
return count;
}
// 逆序排列单词
void reverseWords(char *str) {
int len = strlen(str);
int start = 0, end = 0;
// 去除开头的空格
while (isspace(str[start])) start++;
// 去除结尾的空格
while (len > 0 && isspace(str[len - 1])) len--;
str[len] = '\0';
for (int i = start; i <= len; i++) {
if (isspace(str[i]) || str[i] == '\0') {
end = i - 1;
// 逆序单词
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
start = i + 1;
while (isspace(str[start])) start++;
i = start - 1;
}
}
// 整体逆序字符串
start = 0;
end = len - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}