c语言实现给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初 始顺序。 输入: "Let's take LeetCode contest" 输出: "s'teL ekat edoCteeL tsetnoc"
时间: 2023-05-20 10:01:59 浏览: 102
C语言指针实现字符串的反转
以下是C语言实现给定一个字符串,反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序的代码:
```c
#include <stdio.h>
#include <string.h>
void reverse(char *s, int start, int end) {
while (start < end) {
char temp = s[start];
s[start++] = s[end];
s[end--] = temp;
}
}
char *reverseWords(char *s) {
int len = strlen(s);
int start = 0, end = 0;
while (end <= len) {
if (s[end] == ' ' || s[end] == '\0') {
reverse(s, start, end - 1);
start = end + 1;
}
end++;
}
return s;
}
int main() {
char s[] = "Let's take LeetCode contest";
printf("%s\n", reverseWords(s));
return 0;
}
```
输出结果为:"s'teL ekat edoCteeL tsetnoc"
阅读全文