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

C语言不使用string.h交换字符串数组仅换首字符,求错误排查

字符串交换代码的错误分析与修正

你的代码之所以只交换了两个字符串的首字符,核心问题出在strswap函数的实现上:

  • 函数里的*str1和*str2访问的是两个字符串数组的第一个元素(首字符),你只完成了这单个字符的交换,完全没处理字符串后续的内容,所以运行后只会看到首字符互换,后面的字符保持原样。

要实现整个字符串的交换,需要遍历两个字符串的每一个字符,逐个完成交换,直到碰到字符串结束符'\0'。修正后的代码如下:

#include <stdio.h>
#define SIZE 25

void strswap(char [], char []);

int main(void)
{
    char str1 [SIZE], str2 [SIZE];
    printf("enter the first string for strswap: ");
    scanf("%s", str1);
    printf("enter the second string for strswap: ");
    scanf("%s", str2);
    strswap(str1, str2);
    printf("after strswap, the first string is %s, the second string is %s\n", str1, str2);
    return 0;
}

void strswap(char str1 [], char str2 [])
{
    char temp;
    int i = 0;
    // 逐个交换字符,直到两个字符串都到结束符,同时避免数组越界
    while (str1[i] != '\0' || str2[i] != '\0')
    {
        temp = str1[i];
        str1[i] = str2[i];
        str2[i] = temp;
        i++;
        if (i >= SIZE - 1)
            break;
    }
    // 确保字符串末尾有结束符,避免输出乱码
    str1[i] = '\0';
    str2[i] = '\0';
}

测试示例:

输入第一个字符串:apple
输入第二个字符串:hello
运行结果:after strswap, the first string is hello, the second string is apple

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:35:34