首页 > 解决方案 > 如何在生成的连接字符串中包含空格('')?

问题描述

分配给我的问题是,当给出连接字符串的输出时,第一个和第二个字符串之间必须有一个空格'',而且,禁止使用内置函数“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);

}

标签: stringloopsuser-defined-functionsstring-concatenationstring.h

解决方案


如果允许使用内置的 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);
}

推荐阅读