2013-02-12 80 views
0

我试图找到一种方法将字符串转换为c字符串数组。 因此,例如我的字符串是:将std :: string转换为c字符串数组

std::string s = "This is a string." 

,然后我想输出是这样的:

array[0] = This 
array[1] = is 
array[2] = a 
array[3] = string. 
array[4] = NULL 
+1

http://stackoverflow.com/questions/236129/splitting-a-string-in-c – 2013-02-12 01:06:06

+11

也就是说字符串,而不是字符数组。 – 2013-02-12 01:06:07

+0

所以你有一个'std :: string'的数组?像'std :: string strings [5];'? – 2013-02-12 01:06:10

回答

-2

在你的榜样。

该数组不是一个字符数组,它是一个字符串数组。

实际上,一个字符串是一个字符数组。

//Let's say: 
string s = "This is a string."; 
//Therefore: 
s[0] = T 
s[1] = h 
s[2] = i 
s[3] = s 

但基于你的榜样,

我想你要拆分的文本。 (用SPACE作为分隔符)。

您可以使用字符串的拆分功能。

string s = "This is a string."; 
string[] words = s.Split(' '); 
//Therefore: 
words[0] = This 
words[1] = is 
words[2] = a 
words[3] = string. 
+3

你将不得不泄露哪个** C++ **标准规定'std :: string'的Split()成员。这不是Java。 – WhozCraig 2013-02-12 01:24:15

1

分裂您的字符串转换为基于使用Boost库函数的分隔符多个字符串“拆分”是这样的:

#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

而且有办法过多这里:Split a string in C++?

1

您正在试图将字符串分割成字符串。尝试:

#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; 
    } 

或参阅本split

+0

我试着用你的例子,但我得到这个“错误:变量”std :: stringstream ss'有初始化,但不完整的类型“ – 2013-02-12 01:41:44

+0

你需要包括必要的标题,看我更新的答案 – billz 2013-02-12 01:42:41

+0

啊,我有其他3我只是错过了流。非常感谢,这是一个很大的帮助。 – 2013-02-12 01:47:23

相关问题