gpt4 book ai didi

c - C 中的数组和 strpbrk

转载 作者:太空宇宙 更新时间:2023-11-04 06:05:03 24 4
gpt4 key购买 nike

如果我的数组是:

char* String_Buffer = "Hi my name is <&1> and i have <&2> years old."
char* pos = strpbrk(String_buffer, "<");

现在位置是:

" <&1> and i have <&2> years old. "

但我需要“嗨,我的名字是”。如何做到这一点?

最佳答案

首先,确保您正在使用的字符串在可修改的内存中1:

char String_Buffer[] = "Hi my name is <&1> and i have <&2> years old."

然后,在找到< 的位置剪切字符串:

char* pos = strpbrk(String_buffer, "<");
if(pos!=NULL)
{
/* changing the '<' you found to the null character you are actually
* cutting the string in that place */
*pos=0;
}

打印 String_Buffer现在将输出 Hi my name is .如果你不想要最后的空间,只需移动 pos向后一个元素(注意不要在 String_Buffer 的开头之前)。


  1. 在你的代码中你声明了一个char指针并使其指向不可修改的字符串文字(这就是为什么您通常编写 const char * str = "asdasads"; ;在这种情况下,我们是初始化本地 char 数组,我们可以根据需要对其进行更改。

关于c - C 中的数组和 strpbrk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11888082/

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