#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。
发布于 2021-05-31 20:20:55
试试这个,我创建了一个函数"my_strlen“来获得字符串的大小。
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int my_strlen(char *str)
{
int i;
for (i = 0; str[i] != '\0'; i++);
return (i);
}
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=my_strlen(s1),y=my_strlen(s2);
char cs1[x+y+1];
char cs2[x+y+1];
for (int i = 0; s1[i] != '\0'; i++)
{
cs1[i]=s1[i];
}
for (int i = 0; s2[i] != '\0'; i++)
{
cs1[i + x] = s2[i];
}
for (int i = 0; s2[i] != '\0'; i++)
{
cs2[i] = s2[i];
}
for(int i = 0; s1[i] != '\0'; i++)
{
cs2[i + y] = 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);
}发布于 2021-05-31 20:20:40
这些任务:
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 (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];
}发布于 2021-05-31 20:17:08
x=sizeof(s1),y=sizeof(s2);的大小不会给出字符串的长度
使用函数strlen代替。
您的for循环也是错误的
for (size_t i = 0; i < x; i++)
{
cs1[i]=s1[i];
}
for (int i = x; i < (x+y); i++)
{
cs1[i]=s2[i - x];
}
for (int i = 0; i < (y); i++)
{
cs2[i]=s2[i];
}
for(int i=y;i<(x+y);i++)
{
cs2[i]=s1[i - y];
}https://stackoverflow.com/questions/67779610
复制相似问题