将一个结构体中的字符串逆序 C语言
时间: 2023-11-08 12:48:00 浏览: 157
要将一个结构体中的字符串逆序,你可以使用以下代码:
```c
#include <stdio.h>
#include <string.h>
struct MyStruct {
char str[100];
};
void reverseString(struct MyStruct* myStruct) {
int len = strlen(myStruct->str);
int i, j;
char temp;
for (i = 0, j = len - 1; i < j; i++, j--) {
temp = myStruct->str[i];
myStruct->str[i] = myStruct->str[j];
myStruct->str[j] = temp;
}
}
int main() {
struct MyStruct myStruct;
strcpy(myStruct.str, "Hello World");
printf("Original string: %s\n", myStruct.str);
reverseString(&myStruct);
printf("Reversed string: %s\n", myStruct.str);
return 0;
}
```
在上面的代码中,`MyStruct` 是一个自定义的结构体,它包含一个字符串成员 `str`。`reverseString` 函数用于将字符串逆序。在 `main` 函数中,我们创建了一个 `MyStruct` 类型的变量 `myStruct`,并将字符串赋值给它。然后,我们调用 `reverseString` 函数来逆序字符串,并打印结果。
输出结果为:
```
Original string: Hello World
Reversed string: dlroW olleH
```
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)