3. (简答题)编写一个程序来反转字符串,而不使用 string.h 库中定义的and函数。 strlen() strrev() 下面是一个运行示例。 ------------------------------------ 输入字符串:南京 反向字符串:gnijnaN
时间: 2023-08-15 11:21:12 浏览: 56
好的,以下是C语言的实现代码:
```c
#include <stdio.h>
// 函数声明
void reverse(char str[]);
int main()
{
char str[100];
printf("输入字符串:");
scanf("%s", str);
reverse(str);
printf("反向字符串:%s\n", str);
return 0;
}
// 函数定义
void reverse(char str[])
{
int len = 0;
while (str[len] != '\0') // 获取字符串长度
{
len++;
}
for (int i = 0; i < len / 2; i++) // 反转字符串
{
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}
```
该程序读入一个字符串,然后通过 `reverse()` 函数将其反转,最后输出反转后的字符串。
需要注意的是,该程序没有使用 C 语言标准库中定义的 `string.h` 库中的 `strlen()` 和 `strrev()` 函数,而是通过手动编写代码实现了字符串反转的功能。
相关问题
使用string.h中的字符串长度函数strlen()获得1中的字符串的长度并逆序打印
好的,您可以这样编写代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "这是一个测试字符串";
int len = strlen(str);
for (int i = len-1; i >= 0; i--) {
printf("%c", str[i]);
}
return 0;
}
```
这个程序中,我们首先定义了一个字符串 `str`,然后使用 `strlen()` 函数获取它的长度,并将结果保存在变量 `len` 中。接着,我们使用一个循环从字符串尾部开始,逐个字符地输出它们,直到打印完整个字符串。
输出结果为:`串符字测试个一是这`
使用string.h中的字符串长度函数strlen()获得字符串的长度,并逆序打印;
好的,下面是使用 `strlen()` 函数获取字符串长度,并逆序打印的代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
return 0;
}
```
运行结果如下:
```
!dlroW ,olleH
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)