【问题标题】:Parsing a character array with several null terminated characters into different strings - C++将具有多个空终止字符的字符数组解析为不同的字符串 - C++
【发布时间】:2011-12-30 03:10:46
【问题描述】:

我以前问过这个问题,但信息比现在少。

我基本上拥有的是一个 char 类型的数据块。该块包含我需要格式化并放入向量中的文件名。我最初认为这个字符块的形成在每个文件名之间有三个空格。现在,我意识到它们是 '/0' 以空字符结尾的字符。因此,当我认为存在空格而不是空字符时,所提供的解决方案非常适合我给出的示例。

这是结构的样子。另外,我应该指出我确实有字符数据块的大小。

filename1.bmp/0/0/0brick.bmp/0/0/0toothpaste.gif/0/0/0

最好的解决方案是这样的:

// The stringstream will do the dirty work and deal with the spaces.
   std::istringstream iss(s);

   // Your filenames will be put into this vector.
   std::vector<std::string> v;

   // Copy every filename to a vector.
   std::copy(std::istream_iterator<std::string>(iss),
    std::istream_iterator<std::string>(),
    std::back_inserter(v));

   // They are now in the vector, print them or do whatever you want with them!
   for(int i = 0; i < v.size(); ++i)
    std::cout << v[i] << "\n"; 

这对我原来的问题非常有用,但不是因为它们是空字符而不是空格。有什么办法可以使上面的例子工作。我尝试用空格替换数组中的空字符,但这没有用。

关于将此字符块格式化为字符串向量的最佳方法有什么想法吗?

谢谢。

【问题讨论】:

    标签: c++ vector format char


    【解决方案1】:

    如果您知道您的文件名中没有嵌入“\0”字符,那么这应该可以。 (未经测试)

    const char * buffer = "filename1.bmp/0/0/0brick.bmp/0/0/0toothpaste.gif/0/0/0";
    int size_of_buffer = 1234; //Or whatever the real value is
    
    const char * end_of_buffer = buffer + size_of_buffer;
    
    std::vector<std::string> v;
    
    while( buffer!=end_of_buffer)
    {
      v.push_back( std::string(buffer) );
      buffer = buffer+filename1.size()+3;
    }
    

    如果他们确实在文件名中嵌入了空字符,那么您需要更聪明一点。 像这样的东西应该工作。 (未经测试)

    char * start_of_filename = buffer;
    while( start_of_filename != end_of_buffer )
    {
    
      //Create a cursor at the current spot and move cursor until we hit three nulls
      char * scan_cursor = buffer;
      while( scan_cursor[0]!='\0' && scan_cursor[1]!='\0' && scan_cursor[2]!='\0' )
      {
         ++scan_cursor;
      }
    
      //From our start to the cursor is our word.
      v.push_back( std::string(start_of_filename,scan_cursor) );
    
      //Move on to the next word
      start_of_filename = scan_cursor+3;
    }
    

    【讨论】:

      【解决方案2】:

      如果空格是合适的分隔符,您可以将空字符替换为空格:

      std::replace(std::begin(), std::end(), 0, ' ');
      

      ...然后从那里出发。但是,我怀疑您确实需要使用空字符作为分隔符,因为文件名通常可以包含空格。在这种情况下,您可以使用 std::getline() 和 '\0' 作为行尾,也可以使用字符串本身的 find() 和 substr() 成员。后者看起来像这样:

      std::vector<std::string> v;
      std::string const null(1, '\0');
      for (std::string::size_type pos(0); (pos = s.find_first_not_of(null, pos)) != s.npos; )
      {
          end = s.find(null, pos);
          v.push_back(s.substr(0, end - pos));
          pos = end;
      }
      

      【讨论】:

      • 感谢您提出在名称中可能包含空格的想法。避免了可能的重大头痛。
      猜你喜欢
      • 2018-09-16
      • 1970-01-01
      • 2019-05-09
      • 2012-01-11
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多