【问题标题】:Splitting a character array into strings将字符数组拆分为字符串
【发布时间】:2011-12-23 09:53:18
【问题描述】:

这是我上一个问题的后续。

Parsing file names from a character array

答案是相关的,但我仍然遇到问题。当字符串被拆分时,我似乎无法让它们以字符串或 cstring 的形式正确输出到我的错误日志中,老实说,我并不完全理解他的答案是如何工作的。那么有没有人对这位先生提供的答案有进一步的解释。我将如何将字符数组拆分为更多的字符串,而不仅仅是将它们全部写出来。这就是答案。

std::istringstream iss(the_array);
std::string f1, f2, f3, f4;
iss >> f1 >> f2 >> f3 >> f4;

假设我有 30 个不同的字符串。当然,我不会写 f1, f2....f30。

关于如何做到这一点的任何建议?

【问题讨论】:

  • 如果您需要澄清,请对答案发表评论。
  • 另外请停止签名帖
  • @TomalakGeret'kal 签名帖子?
  • @PladniusBrooks 你不需要写“谢谢”之类的东西。或“”或问题末尾的任何内容。那就是签名帖。

标签: c++ string split


【解决方案1】:

如果愿意,您甚至可以避免显式的 for 循环,并尝试一种对现代 C++ 更自然的方法。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
#include <iterator>

int main()
{
   // Your files are here, separated by 3 spaces for example.
   std::string s("picture1.bmp   file2.txt   random.wtf   dance.png");

   // 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";
}

这是处理“我有 30 个不同的字符串”这样的场景的明显方法。将它们全部存储在某个地方,一个 std::vector 可能是合适的,这取决于您可能想要对文件名做什么。这样您就不需要为每个字符串命名(f1、f2、...),例如,如果需要,您可以通过向量的索引来引用它们。

【讨论】:

    猜你喜欢
    • 2012-02-22
    • 2016-04-01
    • 2011-01-10
    • 2012-06-27
    • 1970-01-01
    • 2011-11-26
    相关资源
    最近更新 更多