C++ 翻转字符串里面的单词 代码
时间: 2023-03-28 09:04:46 浏览: 149
翻转字符串里的单词.md
以下是 C 语言翻转字符串里面的单词的代码:
```c
#include <stdio.h>
#include <string.h>
void reverse(char *start, char *end) {
char temp;
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
}
void reverseWords(char *s) {
char *wordStart = NULL;
char *temp = s;
while (*temp) {
if (wordStart == NULL && *temp != ' ') {
wordStart = temp;
}
if (wordStart && (*(temp + 1) == ' ' || *(temp + 1) == '\')) {
reverse(wordStart, temp);
wordStart = NULL;
}
temp++;
}
reverse(s, temp - 1);
}
int main() {
char str[] = "hello world";
printf("Original string: %s\n", str);
reverseWords(str);
printf("Reversed string: %s\n", str);
return ;
}
```
以上代码可以翻转字符串里面的单词,例如将 "hello world" 翻转为 "world hello"。
阅读全文