将字符数组拆分为字符串
Splitting a character array into strings
这是我上一个问题的后续问题。
从字符数组解析文件名
答案是相关的,但我仍然有麻烦。当字符串被分割时,我似乎无法将它们作为字符串或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,…),如果需要的话,你可以通过向量的索引来引用它们,例如
相关文章:
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 将字符串拆分为等长 c++ 的部分
- 如何使用 Boost C++ 打印第 n 个字符串拆分?
- 我在将字符串拆分为向量时遇到困难
- C++ 如何将字符串拆分为单个字符
- 是否有用于执行反向字符串拆分器的开箱即用功能?
- 如何将字符串拆分为一组 3 个字符,它们之间有空格
- 将字符串拆分为单个单词并将它们放置在向量中
- 基于其中的数字子字符串拆分字符串
- 如何在C++中将数字字符串拆分为数组
- 如何在 c++ 中将字符串拆分为字符串 2d 数组数组
- 如何将标准::字符串拆分为标准::string_views的范围 (v3)
- 将特定格式的字符串拆分为浮点数和字符串
- 在 c++ 中将字符串拆分为单独的变量
- 用C 中的4个字符将字符串拆分
- 如何用Arduino中的另一个字符串将字符串拆分
- 如何在 Main 方法之外将字符串拆分为标记
- C 将字符串按空白空间将字符串拆分,除非将其封闭在引号中并存储在向量中
- 将字符串拆分为矢量 C++
- 试图将字符串拆分为两个整数