首页 > 解决方案 > c中的字符串连接问题

问题描述

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
    int x,y;
    char s1[30],s2[30];
    printf("Enter string 1:");
    scanf("%s",s1);
    printf("Enter string 2:");
    scanf("%s",s2);
    x=sizeof(s1),y=sizeof(s2);
    char cs1[x+y+1];
    char cs2[x+y+1];
    for (int i = 0; i < x; i++)
    {
        cs1[i]=s1[i];
    }
    for (int i =x; i < (x+y); i++)
    {
        cs1[i]=s2[i];
    }
    for (int i = 0; i < (y); i++)
    {
        cs2[i]=s2[i];
    }
    for(int i=y;i<(x+y);i++)
    {
        cs2[i]=s1[i];
    }
    cs1[x+y]='\0';
    cs2[x+y]='\0';
    printf("string 1+string 2 is:%s",cs1);
    printf("\nstring 2+ string 1 :%s",cs2);
    
    
    
    

 





    return 0;
}

我试图在不使用内置函数的情况下连接两个字符串,你能指出错误吗?这是给字符串,因为它们是我的意思是说它正在打印 s1 字符串代替 cs1 和 s2 代替 cs2

标签: cstring

解决方案


这些任务:

 x=sizeof(s1),y=sizeof(s2);

没有意义,因为分配的值不代表输​​入字符串的长度。

你需要写:

#include <string.h>

//...

size_t x,y;
char s1[30],s2[30];
printf("Enter string 1:");
scanf("%s",s1);
printf("Enter string 2:");
scanf("%s",s2);
x = strlen(s1), y = strlen(s2);
//...

这些 for 循环:

for (int i =x; i < (x+y); i++)
{
    cs1[i]=s2[i];
}

//...

for(int i=y;i<(x+y);i++)
{
    cs2[i]=s1[i];
}

不正确。你需要写:

for ( size_t i = 0; i < y; i++)
{
    cs1[i + x] = s2[i];
}

//...

for( size_t i = 0; i < x; i++)
{
    cs2[i + y ] = s1[i];
}

推荐阅读