C语言实现:提取下划线分隔奇数位单词的尾字符与长度并输出
解决C语言中如何返回处理结果并打印的问题
你的思路是对的,现在需要解决两个核心问题:一是处理最后一个单词(原代码循环结束后没处理),二是把结果输出。下面提供两种简单可行的方案:
方案1:直接在函数内打印结果
这种方式最直接,符合你最终要输出结果的需求。修改后的代码会在遇到下划线时(奇数位置单词结束)打印结果,循环结束后再处理最后一个单词:
#include <stdio.h> void str_dummy_encrypt(char *sentence) { int currentWord = 1; int totalChars = 0; char lastChar; // 跟踪当前单词的最后一个字符 for (int i = 0; sentence[i] != '\0'; i++) { if (sentence[i] == '_') { if (currentWord % 2 != 0) { printf("%c%d", lastChar, totalChars); } currentWord++; totalChars = 0; } else { totalChars++; lastChar = sentence[i]; } } // 处理循环结束后的最后一个单词 if (currentWord % 2 != 0) { printf("%c%d", lastChar, totalChars); } printf("\n"); // 可选,根据需要添加换行 } int main() { char sentence[100]; while (scanf("%s", sentence) != EOF) { str_dummy_encrypt(sentence); } return 0; }
方案2:通过输出缓冲区返回结果
如果后续需要对处理后的结果做其他操作(比如保存到文件、进一步修改),可以让函数把结果写入一个输出缓冲区,再由main函数处理:
#include <stdio.h> #include <string.h> // 传入输出缓冲区,函数将结果写入其中 void str_dummy_encrypt(char *sentence, char *output) { int currentWord = 1; int totalChars = 0; char lastChar; int outputPos = 0; // 输出缓冲区的当前写入位置 for (int i = 0; sentence[i] != '\0'; i++) { if (sentence[i] == '_') { if (currentWord % 2 != 0) { // 用snprintf确保不会溢出缓冲区 outputPos += snprintf(output + outputPos, 200 - outputPos, "%c%d", lastChar, totalChars); } currentWord++; totalChars = 0; } else { totalChars++; lastChar = sentence[i]; } } // 处理最后一个单词 if (currentWord % 2 != 0) { outputPos += snprintf(output + outputPos, 200 - outputPos, "%c%d", lastChar, totalChars); } output[outputPos] = '\0'; // 确保字符串以结束符结尾 } int main() { char sentence[100]; char output[200]; // 定义足够大的输出缓冲区 while (scanf("%s", sentence) != EOF) { str_dummy_encrypt(sentence, output); printf("%s\n", output); } return 0; }
关键说明
- 两种方案都补上了最后一个单词的处理:原代码循环到字符串结束时,不会处理最后一个单词,必须单独判断。
- 用
lastChar跟踪当前单词的最后一个字符,比直接用sentence[i-1]更清晰安全,避免索引越界风险。
内容的提问来源于stack exchange,提问作者TJ is too short
相关产品推荐
相关产品推荐

