gpt4 book ai didi

C 字符串打印超出范围

转载 作者:行者123 更新时间:2023-11-30 19:32:55 25 4
gpt4 key购买 nike

只要在其中找到子字符串 aaa,此代码就会中断主字符串 stringone。此代码正在执行此操作,但它打印出边界并且不会在空字符处停止。

我得到的输出是这样的

who cares if 
one more light goes out
in the sky of a million
stars,
well i do if the star is you
;<@����P����p���Xz��������p���0zRx
����+zRx
�$����FJ
�?;*}D���� \�����A�C
D|���eB�B�E �B(�H0�H8�M@r8A0A(B BB�8����p

我不明白为什么,我是否跳过更新字符串的行中的 NULL 字符?

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

int main()
{

char *stringone = "who cares if aaa one more light goes out aaa in the sky of a million aaa stars, aaa well i do if the star is you \0";

char *breaker = "aaa";

while(stringone)
{
while(stringone != strstr(stringone, breaker) || stringone == NULL)
{
printf("%c",*stringone);
stringone++;
}

stringone = stringone + strlen(breaker) + 1;
printf("\n");
}
return 0;
}

最佳答案

您应该使用 strtok 函数。请参阅示例:

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

int main() {
char stringone[200] = "who cares if aaa one more light goes out aaa in the sky of a million aaa stars, aaa well i do if the star is you";
char breaker[10] = "aaa";
char *token = strtok(stringone, breaker);

while (token != NULL) {
printf("\n %s", token);
token = strtok(NULL, breaker);
}
return 0;
}

关于C 字符串打印超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46581731/

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