写一个字符串倒序的c代码
时间: 2024-05-02 08:19:21 浏览: 13
下面是将字符串倒序的 C 代码:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, len;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
printf("反转后的字符串:");
for(i=len-1; i>=0; i--)
{
printf("%c", str[i]);
}
return 0;
}
```
注:该代码可以将用户输入的字符串倒序输出。
相关问题
c代码 将一个字符串倒序
以下是将一个字符串倒序的 C 代码:
```c
#include <stdio.h>
#include <string.h>
void reverse_string(char *str) {
int length, i;
char temp;
length = strlen(str);
for (i = 0; i < length/2; i++) {
temp = str[i];
str[i] = str[length-i-1];
str[length-i-1] = temp;
}
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // remove newline character from string
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
这个程序首先读入一个字符串,然后利用一个 for 循环将字符串中的字符倒序排列,最后输出倒序后的字符串。
用c 将一个字符串倒序
可以使用数组和循环来实现字符串倒序,具体代码如下:
```c
#include <stdio.h>
#include <string.h>
void reverse(char s[]) {
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
char temp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = temp;
}
}
int main() {
char str[] = "hello world";
reverse(str);
printf("%s\n", str); // 输出 "dlrow olleh"
return 0;
}
```
首先通过 `strlen` 函数获取字符串的长度,然后通过循环将字符串的前半部分与后半部分进行交换,从而实现字符串的倒序。最后通过 `printf` 函数输出倒序后的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)