gpt4 book ai didi

c++ - 在 Enter 键处拆​​分字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:01:00 25 4
gpt4 key购买 nike

我正在从编辑框中获取文本,我希望通过回车键分隔每个名称,例如下面带有 NULL 字符的字符串。

    char *names = "Name1\0Name2\0Name3\0Name4\0Name5";

while(*names)
{
names += strlen(names)+1;
}

你会如何对回车键做同样的事情(即用/r/n 分隔)?你能不使用 std::string 类来做到这一点吗?

最佳答案

使用字符串:

while (*names)
{
char *next = strstr(names, "\r\n");
if (next != NULL)
{
// If you want to use the key, the length is
size_t len = next - names;

// do something with a string here. The string is not 0 terminated
// so you need to use only 'len' bytes. How you do this depends on
// your need.

// Have names point to the first character after the \r\n
names = next + 2;
}
else
{
// do something with name here. This version is 0 terminated
// so it's easy to use

// Have names point to the terminating \0
names += strlen(names);
}
}

需要注意的是,此代码还修复了代码中的一个错误。您的字符串以单个\0 终止,因此最后一次迭代的名称将指向您的字符串之后的第一个字节。要修复现有代码,您需要将名称的值更改为:

// The algorithm needs two \0's at the end (one so the final
// strlen will work and the second so that the while loop will
// terminate). Add one explicitly and allow the compiler to
// add a second one.
char *names = "Name1\0Name2\0Name3\0Name4\0Name5\0";

关于c++ - 在 Enter 键处拆​​分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2216160/

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