用指针实现字符串单词逆置
时间: 2023-04-05 10:00:29 浏览: 88
可以使用指针实现字符串单词逆置,具体实现方法如下:
```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 *str) {
char *word_start = NULL;
char *temp = str;
while (*temp) {
if ((word_start == NULL) && (*temp != ' ')) {
word_start = temp;
}
if (word_start && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0'))) {
reverse(word_start, temp);
word_start = NULL;
}
temp++;
}
reverse(str, temp - 1);
}
int main() {
char str[] = "I love China";
printf("Original string: %s\n", str);
reverseWords(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
这段代码可以将字符串中的单词逆置,例如将"I love China"逆置为"China love I"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![torrent](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)