【问题标题】:How can i include a space (' ') in the resulting concatenated string?如何在生成的连接字符串中包含空格('')?
【发布时间】:2021-03-25 17:29:37
【问题描述】:

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

}

【问题讨论】:

  • 您有 1 个错误。你需要先初始化i = 0
  • sprintf() 也被禁止了吗?顺便说一句,有趣的是 strcat() 被禁止但不是 gets() 被每个(好的)手册禁止并最终从 C 标准中删除......你的编译器没有告诉你不要使用它吗?跨度>

标签: string loops user-defined-functions string-concatenation string.h


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-04-13
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多