输出逆置字符串

文章提供了一个C语言程序,用于接受用户输入的小写字母字符串并进行原地反转。程序首先读取一行不超过1000个字符的字符串,然后使用一个临时变量在原数组中进行字符交换来实现反转。错误代码部分展示了尝试创建一个独立函数进行字符串反转,但未能正确传递和处理字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

接受一个只包含小写字母的字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)

题目来源

输入描述

输入一行,为一个只包含小写字母的字符串。

输出描述

输入一行,为一个只包含小写字母的字符串。

思路

输入后用一个临时变量tmp进行原地逆置

具体实现:

#include <stdio.h>
#include <string.h>

int main(void)
{
    printf("请输入一行不超过1000个字符的字符串\n");
    char st[1000] = {};
    char tmp=NULL;
    for (int i = 0; i < 1000; i++)
    {
        st[i] = getchar();
        if (st[i] == '\n')
        {
            st[i] = '\0';
            break;
        }
    }
    int c = (strlen(st)-1);
    int d = 0;
    for (; c>d; c--)
    {
        tmp = st[c];
        st[c] = st[d];
        st[d] = tmp;
        d++;
    }
    printf("逆置为:%s\n",st);
    return 0;
}

小结:对函数如何传入字符串不明确,以下是错误代码

未解决:

#include <stdio.h>
#include <string.h>

char* Reverse_1(char s[])//原地逆置
{
    char* add = s;
    int a = (strlen(s)-1);
    int b = 0;
    char str1[1000] = {};
    char c; 
    for (; a > b; a--)
    {
        c = str1[a];
        str1[a] = str1[b];
        str1[b] = c;
        b++;
    }
    return add;
}

int main(void)
{
    printf("请输入一行不超过1000个字符的字符串\n");
    char st[1000] = {};
    for (int i = 0; i < 1000; i++)
    {
        st[i] = getchar();
        if (st[i] == '\n')
        {
            st[i] = '\0';
            break;
        }
    }
    int c = strlen(st);
    char st2[1000] = {};
    st2[c] = *Reverse_1(&st[c]);
    printf("逆置为:%s\n",st2);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值