将std::字符串转换为c字符串数组
converting a std::string to an array of c strings
我正试图找到一种将字符串转换为c字符串数组的方法。例如,我的字符串是:
std::string s = "This is a string."
然后我希望输出是这样的:
array[0] = This
array[1] = is
array[2] = a
array[3] = string.
array[4] = NULL
您正试图将字符串拆分为多个字符串。尝试:
#include <sstream>
#include <vector>
#include <iostream>
#include <string>
std::string s = "This is a string.";
std::vector<std::string> array;
std::stringstream ss(s);
std::string tmp;
while(std::getline(ss, tmp, ' '))
{
array.push_back(tmp);
}
for(auto it = array.begin(); it != array.end(); ++it)
{
std::cout << (*it) << std:: endl;
}
或者查看此拆分
使用Boost库函数"Split"根据分隔符将字符串拆分为多个字符串,如下所示:
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of(" "));
然后对strs
向量进行迭代。
这种方法允许您指定任意数量的分隔符。
查看此处了解更多信息:http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768
这里有很多方法:用C++拆分字符串?
在您的示例中。
数组不是字符数组,而是字符串数组。
实际上,字符串是一个字符数组。
//Let's say:
string s = "This is a string.";
//Therefore:
s[0] = T
s[1] = h
s[2] = i
s[3] = s
但根据你的例子,
我想你想把文本分开。(以SPACE作为delimeter)。
您可以使用字符串的拆分功能。
string s = "This is a string.";
string[] words = s.Split(' ');
//Therefore:
words[0] = This
words[1] = is
words[2] = a
words[3] = string.
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组