在Enter键处拆分字符串

时间:2010-02-07 06:21:45

标签: c++

我从editbox获取文本,我想让每个名字用输入键分隔,如下面的字符串,用NULL字符。

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

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

你如何对enter键做同样的事情(即用/ r / n分隔)?你可以不使用std :: string类吗?

4 个答案:

答案 0 :(得分:2)

使用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";

答案 1 :(得分:0)

如果你想用C字符串开始和结束,那它就不是C ++。

这是strsep的工作。

#include <stdlib.h>
void split_string( char *multiline ) {
    do strsep( &multiline, "\r\n" );
    while ( multiline );
}

strsep的每次调用都会将\r\n归零。由于只显示字符串\r\n,因此每个其他调用都将返回一个参数。如果您愿意,可以通过在char*前进时记录multilinestrsep的返回值来构建void split_string( char *multiline ) { vector< char* > args; do { char *arg = strsep( &multiline, "\r\n" ); if ( * arg != 0 ) { args.push_back( arg ); } } while ( multiline ); } 数组。

{{1}}

第二个例子至少不是Windows特有的。

答案 2 :(得分:0)

这是一个纯粹的指针解决方案

   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);

答案 3 :(得分:0)

由于它具有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 
相关问题