gpt4 book ai didi

c - 在 C 中查找子字符串

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:26 25 4
gpt4 key购买 nike

我想从一个带有签名的函数的字符数组中提取一个子字符串:

void substring (char str[], int start, int count, char result[]);

这是我的尝试:

void substring (char str[], int start, int count, char result[])
{
int i;

int j = 0;
for(i = start; i <= count; i++)
{
result[j] = str[i];
j++;
printf("the character in function call : %c \n", result[j]);
printf("the count of j is : %i \n", j);
}
result[j] = '\0';
printf("the result function call : %s \n", result);
}

int main (void)
{
char pet[] = "character";
char result[40];

substring (pet, 4, 3, result);

printf("the substring of character from 4, 3 step ahead is : %s \n", result);

return 0;
}

但是我在控制台窗口中没有得到任何结果。我在网上找到了另一种带有 while 循环的方法,但我仍然认为我的代码应该可以工作。为什么我的代码不起作用?

最佳答案

问题出在这一行:

for(i = start; i <= count; i++)

第一次进入这个for循环,i为4,小于count的值为3,所以它退出循环并且不打印任何内容。

你必须改变它:

for(i = start; i < start + count; i++)

关于c - 在 C 中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352673/

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