酷代码 AI
菜单
服务商

C-1 句子反转 分数 30 作者 陈宇璟 单位 浙江大学 给定一行句子,每个词之间用空格隔开,要么是全小写英文单词,要么是全大写英文单词,要么是自然数。 要求将这些单词倒序输出。而且对于每个单词,如果是小写词,应当转为大写;如果是大写词,应当转为小写;如果是自然数,应该倒转输出。 举一个例子: we choose to go 2 the 123 moon 程序应当输出: moon 321 the 2 go to choose we 输入格式 仅一行,即需要反转的句子。 输出格式 仅一行,表示程序对句子的处理结果。 说明/提示 样例解释 首先应当按单词逆序,即: moon 123 the 2 go to choose we 小写变大写、大写变小写、倒转自然数之后,得到最终结果: moon 321 the 2 go to choose we 数据规模与约定 对于 100% 的数据,句子中包含的单词数量不超过 1000,每个单词长度不超过 6。 输入样例: we choose to go 2 the 123 moon 输出样例: moon 321 the 2 go to,用C语言完成

#include <stdio.h> #include <string.h> #include <ctype.h> // 判断一个字符串是否为自然数 int is_number(char *s) { for (int i = 0; s[i]; i++) { if (!isdigit(s[i])) { return 0; } } return 1; } // 反转一个字符串 void reverse_string(char *s) { int len = strlen(s); for (int i = 0; i < len / 2; i++) { char temp = s[i]; s[i] = s[len - 1 - i]; s[len - 1 - i] = temp; } } // 处理单个单词:小写转大写,大写转小写,数字反转 void process_word(char *word) { if (is_number(word)) { reverse_string(word); return; } int has_lower = 0, has_upper = 0; for (int i = 0; word[i]; i++) { if (islower(word[i])) has_lower = 1; if (isupper(word[i])) has_upper = 1; } // 全小写 -> 转大写 if (has_lower && !has_upper) { for (int i = 0; word[i]; i++) { word[i] = toupper(word[i]); } } // 全大写 -> 转小写 else if (has_upper && !has_lower) { for (int i = 0; word[i]; i++) { word[i] = tolower(word[i]); } } } int main() { char line[10000]; fgets(line, sizeof(line), stdin); // 去掉换行符 int len = strlen(line); if (len > 0 && line[len - 1] == '\n') { line[len - 1] = '\0'; } // 拆分单词 char *words[1000]; int word_count = 0; char temp_line[10000]; strcpy(temp_line, line); char *token = strtok(temp_line, " "); while (token != NULL) { words[word_count] = (char *)malloc(strlen(token) + 1); strcpy(words[word_count], token); word_count++; token = strtok(NULL, " "); } // 倒序处理并输出 for (int i = word_count - 1; i >= 0; i--) { process_word(words[i]); printf("%s", words[i]); if (i > 0) printf(" "); } printf("\n"); // 释放内存 for (int i = 0; i < word_count; i++) { free(words[i]); } return 0; } 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: - 输入字符串可能包含多个连续空格,需确保使用正确的分词方式避免出错。 - 动态分配内存后必须正确释放,防止内存泄漏。 - 数字反转时要确保只对纯数字字符串操作,避免将含字母的字符串误判为数字。 [2025-10-25 11:35:19 | AI写代码神器 | 712点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多