将字符数组拆分为字符串

Splitting a character array into strings

本文关键字:字符串 拆分 数组 字符      更新时间:2023-10-16

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

从字符数组解析文件名

答案是相关的,但我仍然有麻烦。当字符串被分割时,我似乎无法将它们作为字符串或cstring正确地输出到我的错误日志中,说实话,我不完全理解他的答案是如何工作的。有人能进一步解释这位先生给出的答案吗?如何将字符数组拆分为更大数量的字符串,而不是将它们全部写出来。这就是答案。

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

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

有什么建议吗?

如果你愿意的话,你甚至可以避免显式的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,…),如果需要的话,你可以通过向量的索引来引用它们,例如