C语言实现句子反转输出的多种方法及性能比较211


在C语言编程中,实现句子反转输出是一个常见的编程练习题,它考察了程序员对字符串操作、指针、数组以及算法的理解。本文将深入探讨几种不同的C语言实现方法,并对它们的性能进行比较,帮助读者选择最优方案。

方法一:使用循环和辅助数组

这是最直观的一种方法。我们首先遍历输入字符串,将单词逐个存储到一个辅助数组中,然后反向遍历辅助数组,并将单词输出,从而实现句子反转。这种方法需要额外的内存空间来存储辅助数组。```c
#include
#include
#define MAX_WORDS 100
#define MAX_WORD_LENGTH 50
void reverseSentence(char *sentence) {
char words[MAX_WORDS][MAX_WORD_LENGTH];
int wordCount = 0;
char *word = strtok(sentence, " "); // 分割单词
while (word != NULL) {
strcpy(words[wordCount++], word);
word = strtok(NULL, " ");
}
for (int i = wordCount - 1; i >= 0; i--) {
printf("%s ", words[i]);
}
printf("");
}
int main() {
char sentence[] = "This is a sample sentence.";
reverseSentence(sentence); // Output: sentence. sample a is This
return 0;
}
```

方法二:使用指针和递归

这种方法利用指针操作和递归函数来实现句子反转。递归函数从字符串的末尾开始遍历,找到单词的边界,然后递归处理剩余部分。这种方法比较简洁,但递归深度可能导致栈溢出,尤其是在处理非常长的句子时。```c
#include
#include
void reverseWordsRecursive(char *str) {
if (*str == '\0') return;
char *end = str;
while (*end != ' ' && *end != '\0') end++;
reverseWordsRecursive(end + (*end == ' ' ? 1 : 0));
while (end > str && *end != ' ') end--;
printf("%.*s ", (int)(end - str), str);
}

int main() {
char sentence[] = "This is a sample sentence.";
reverseWordsRecursive(sentence); // Output: sentence. sample a is This
printf("");
return 0;
}
```

方法三:原地反转(In-place reversal)

为了提高效率和减少内存消耗,我们可以尝试原地反转字符串。这个方法需要先反转整个句子,然后反转每个单词。这避免了额外的内存分配,但是代码复杂度略高。```c
#include
#include
void reverseString(char *str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
void reverseSentenceInPlace(char *sentence) {
int len = strlen(sentence);
reverseString(sentence, 0, len - 1); // Reverse the whole sentence
int start = 0;
for (int i = 0; i

2025-05-29


上一篇:C语言中:逆序输出详解及多种实现方法

下一篇:C语言实现倒序输出数字的多种方法及详解