我从编辑框中获取文本,并希望通过输入键分隔每个名称,如下面的字符串与空字符一样。在输入键中分割字符串
char *names = "Name1\0Name2\0Name3\0Name4\0Name5";
while(*names)
{
names += strlen(names)+1;
}
你会如何做相同的输入密钥(即分隔/ r/n)?你可以做到这一点,而不使用std :: string类吗?
我从编辑框中获取文本,并希望通过输入键分隔每个名称,如下面的字符串与空字符一样。在输入键中分割字符串
char *names = "Name1\0Name2\0Name3\0Name4\0Name5";
while(*names)
{
names += strlen(names)+1;
}
你会如何做相同的输入密钥(即分隔/ r/n)?你可以做到这一点,而不使用std :: string类吗?
使用的strstr:
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字符串结束,它不是真正的C++。
这是strsep
的工作。
#include <stdlib.h>
void split_string(char *multiline) {
do strsep(&multiline, "\r\n");
while (multiline);
}
每次调用strsep
零出无论是\r
或\n
。由于只有字符串\r\n
出现,所有其他呼叫都会返回参数。如果你愿意,你可以通过记录multiline
来创建char*
的数组,因为它前进或返回值为strsep
。
void split_string(char *multiline) {
vector< char* > args;
do {
char *arg = strsep(&multiline, "\r\n");
if (* arg != 0) {
args.push_back(arg);
}
} while (multiline);
}
这第二个例子至少不是特定于Windows。
@Samuel:是的,我考虑了这两件事情。第一个片段的解释说,每个其他'strsep'都会返回一个子字符串。第二个片段删除\ r \ n's生成的空子串。 – Potatoswatter 2010-02-07 07:33:10
这里是一个纯粹的指针解决
char * names = "name1\r\nName2\r\nName3";
char * plast = names;
while (*names)
{
if (names[0] == '\r' && names[1] == '\n')
{
if (plast < names)
{
size_t cch = names - plast;
// plast points to a name of length cch, not null terminated.
// to extract the name use
// strncpy(pout, plast, cch);
// pout[cch] = '\0';
}
plast = names+2;
}
++names;
}
// plast now points to the start of the last name, it is null terminated.
// extract it with
// strcpy(pout, plast);
因为这有C++
标签,最简单的可能会使用C++标准库,尤其是字符串和字符串流。为什么你想在C++中避免std::string
?
std::istringstream iss(names);
std::string line;
while(std::getline(iss,line))
process(line); // do process(line.c_str()) instead if you need to
你需要额外的\ 0在你的字符串末尾或你的while将跑离你的字符串的结尾。 '“.... \ 0Name5 \ 0”' – 2010-02-07 06:35:02
@John Knoeller:当我意识到OP在谈论换行符而不是空字符时,我正要发表该评论。 '\ 0'作为他试图剔除的分隔符的一个例子。 – dirkgently 2010-02-07 06:41:15