问题描述
分配给我的问题说,当给出连接字符串的输出时,它的第一个和第二个字符串之间必须有一个空格' ',并且禁止使用内置函数“strcat()” .例如 String1=Hello,String2=World,ConcatenatedString=Hello(space)World。我需要帮助。谢谢。
void strconcat(char s1[15],char s2[15])
{
int i;
printf("ENTER A STRING : ");
gets(s1);
printf("ENTER A STRING : ");
gets(s2);
while (s1[i] != '\0')
{
i++;
}
for (int j = 0; s2[j] != '\0'; j++,i++)
{
s1[i] = s2[j];
}
s1[i] = '\0';
puts(s1);
}
解决方法
如果允许您使用内置的 c 函数 size_t strlen(const char *str)
,那么您可以保存第一个 while 循环。
void strconcat(char s1[15],char s2[15])
{
int i = 0; // You have not initialized this in your code.
printf("ENTER A STRING : ");
gets(s1);
printf("ENTER A STRING : ");
gets(s2);
i = strlen(s1); // If the use of in-built strlen is not allowed then just use the below two lines
s1[i] = ' '; // Here i is at the position of '\0' character in s1 array.
i++;
for (int j = 0; s2[j] != '\0'; j++,i++)
{
s1[i] = s2[j];
}
s1[i] = '\0';
puts(s1);
}