2013-02-12 54 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

相關問題