编写一个函数实现字符串中单词的逆序,其他字符保持位置不变 请用C语言实现,至少不少于三种方法
时间: 2023-05-17 07:02:59 浏览: 88
C语言三种方法实现字符串逆序函数
1. 方法一:使用指针和数组实现
```c
#include <stdio.h>
#include <string.h>
void reverseWords(char *str) {
int len = strlen(str);
char *start = str;
char *end = str + len - 1;
char temp;
// Reverse the whole string
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
// Reverse each word in the string
start = end = str;
while (*start) {
while (*end != ' ' && *end != '\0') {
end++;
}
end--;
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
start = ++end;
}
}
int main() {
char str[] = "Hello world, how are you?";
printf("Original string: %s\n", str);
reverseWords(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
2. 方法二:使用 strtok 函数实现
```c
#include <stdio.h>
#include <string.h>
void reverseWords(char *str) {
char *token;
char *delimiter = " ";
char *words[100];
int count = 0;
// Split the string into words
token = strtok(str, delimiter);
while (token != NULL) {
words[count++] = token;
token = strtok(NULL, delimiter);
}
// Reverse the order of the words
for (int i = count - 1; i >= 0; i--) {
printf("%s ", words[i]);
}
printf("\n");
}
int main() {
char str[] = "Hello world, how are you?";
printf("Original string: %s\n", str);
reverseWords(str);
return 0;
}
```
3. 方法三:使用递归实现
```c
#include <stdio.h>
#include <string.h>
void reverseWords(char *str, int start, int end) {
if (start >= end) {
return;
}
// Reverse the whole string
char temp = str[start];
str[start] = str[end];
str[end] = temp;
// Reverse each word in the string
int i = start + 1;
while (i < end && str[i] != ' ') {
i++;
}
reverseWords(str, start + 1, i - 1);
reverseWords(str, i + 1, end);
}
int main() {
char str[] = "Hello world, how are you?";
printf("Original string: %s\n", str);
reverseWords(str, 0, strlen(str) - 1);
printf("Reversed string: %s\n", str);
return 0;
}
```
阅读全文