gpt4 book ai didi

迭代连接两个字符串 - C

转载 作者:行者123 更新时间:2023-11-30 20:14:08 25 4
gpt4 key购买 nike

我想迭代一个字符串(由用户输入),返回输入的字符串,并在每个字符后添加空格。 IE。 “你好”-->“你好”。

我的 C 代码:

#include <stdio.h>
#include <string.h>

int main()
{
char str[] = "";
printf("Enter a string: ");
scanf("%s", &str);

int i = 0;
char newstr[150] = "";

for (i = 0; i < strlen(str); i++)
{
strcat(newstr, str[i]);
strcat(newstr, " ");
}

printf("Expanded String: ");
printf("%s", newstr);

return 0;
}

我的错误如下:

warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast [enabled by default] ----- > strcat(newstr, str[i]);

note: expected ‘const char *’ but argument is of type ‘char’ ----- > char *_EXFUN(strcat,(char *__restrict, const char *__restrict));

我习惯了可以连接字符串索引的 python 语法,这是我的 C 代码出错的地方吗?

最佳答案

for (i = 0; i < strlen(str); i++)
{
newstr[2*i]=str[i];
newstr[2*i+1]=' ';
}
// newstr[2 * strlen(str)] = '\0';
// thanks for the hint - I omit that because
// the whole buffer had been cleared during initialization

关于迭代连接两个字符串 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27714464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com