You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言字符串处理问题:从指定字符反转后仅保留该部分并输出指定字符

C语言字符串反转问题修复

问题描述

编写的C语言程序需求为:读取输入字符串与指定字符,调用reverse2nPart函数从该字符开始反转字符串的后半段并保存至原字符串,同时通过指针输出反转后字符串的第二个字符。但当前程序输出不符合预期:

  • 实际输出保留了指定字符前的内容,预期应仅输出从指定字符开始反转后的部分
  • 第二个字符输出错误

当前程序输入输出

Enter a string: abc123@gmail.com
Enter the character to substring the string: @
The reversed string is: abc123moc.liamg@
The second character in the new reversed string is: b

预期输入输出

Enter a string: abc123@gmail.com
Enter the character to substring the string: @
The reversed string is: moc.liamg@
The second character in the new reversed string is: o

问题分析

  1. 输出范围错误:程序当前打印整个原字符串,未聚焦到反转后的后半段起始位置
  2. 字符位置取错:程序取原字符串的第二个字符,而非反转后半段的第二个字符
  3. 指针丢失问题:反转包含指定字符的后半段后,原指定字符会被移到后半段末尾,无法在反转后通过strchr重新获取正确的后半段起始点,需提前保存反转前的起始指针

修复后的代码

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

void reverse2nPart(char *start) {
    if (start != NULL) {
        int len = strlen(start);
        // 反转从start开始的后半段内容
        for (int i = 0; i < len / 2; i++) {
            char temp = start[i];
            start[i] = start[len - 1 - i];
            start[len - 1 - i] = temp;
        }
    }
}

int main() {
    char inputString[100];
    char ch;

    printf("Enter a string: ");
    scanf("%s", inputString);

    printf("Enter the character to substring the string: ");
    scanf(" %c", &ch);

    // 提前定位指定字符,保存后半段起始指针
    char *partStart = strchr(inputString, ch);

    if (partStart != NULL) {
        reverse2nPart(partStart);
        // 仅输出反转后的后半段
        printf("The reversed string is: %s\n", partStart);
        // 输出后半段的第二个字符,增加边界判断避免非法访问
        if (strlen(partStart) >= 2) {
            printf("The second character in the new reversed string is: %c\n", *(partStart + 1));
        } else {
            printf("The reversed part is too short to have a second character.\n");
        }
    } else {
        printf("Character not found in the string.\n");
    }

    return 0;
}

代码说明

  • 简化反转函数:reverse2nPart直接接收后半段起始指针,专注于反转逻辑,无需重复查找指定字符
  • 提前保存起始指针:在反转前通过strchr定位指定字符,确保反转后能直接输出正确的后半段内容
  • 修正输出逻辑:打印partStart指向的内容而非整个原字符串;通过*(partStart + 1)获取反转后半段的第二个字符
  • 增加边界处理:处理指定字符不存在或后半段长度不足2的情况,避免内存非法访问

内容的提问来源于stack exchange,提问作者Deema

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 09:05:38