【发布时间】:2022-01-11 22:55:54
【问题描述】:
我正在尝试连接 C 中的字符,但没有成功。问题是获取一个字符串,检查该字符串中是否有空格,然后根据该主字符串中空格后面的字母创建一个新字符串。
例子:
主字符串:hello world wide
新字符串:hww
我不知道如何连接。我在互联网上进行了研究,发现strcpy 和strcat 函数很有用,但即使使用它们我也没有成功。同样的,我尝试做类似result += string[i + 1]的事情,但它不起作用。
源代码
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "str ing placeholder";
int stringLength = strlen(string);
int i;
char result;
for (i = 0; i < stringLength; i++)
{
if (string[i] == ' ')
{
printf("Found space at the index: %d\n", i);
result = string[i + 1];
printf("\nNext char: %c\n", result);
}
}
return 0;
}
希望有人可以指导我。我不认为我的程序逻辑有问题,我只需要将字符串的第一个字符和字符串空格后面的每个字符连接成一个新字符串,然后呈现这个新形成的字符串。
【问题讨论】:
-
你的逻辑确实不正确。如果您有多个连续的空格,则此代码无法干净地处理。
-
newstring[index++] = oldstring[firstletter];终于以newstring[index] = '\0';结束 -
@Shi Nha 不清楚是否需要原地更改源字符串或复制到另一个字符数组。