2011-11-23 135 views
1

我想我從來沒有學過這個。我從來沒有這樣做過。我見過使用strcat(S1, S2),但這不適用於此,是嗎?我怎樣才能把多個字符組合成一個字符串

我可以這樣做

string all_possible_strings[10]; 
char jumbled_chars[] = "ABCDEFG"; 
all_possible_strings[1] = jumbled_chars[0] << jumbled_chars[1] 
           << jumbled_chars[2] << jumbled_chars[3] 
           << jumbled_chars[4]; 

我想要做的是使一個程序,可以解讀一個字到它的所有可能的排列。

+0

字母在哪裏開頭?如果他們已經在一個數組中,那麼你所要做的就是追加一個空字符(\ 0),我想。 – llakais

+1

你的問題意味着你不明白C++中的字符串是如何工作的。也許你應該從更基本的一般水平開始?如果您有特定情況需要幫助,請提供詳細信息。 – tenfour

+0

這是行代碼: – Monkeyanator

回答

1

使用append函數或operator+=過載std::string。你應該閱讀STL documentation

如果jumbled_chars已經在你想要的順序,那麼你可以只構建字符串如

all_possible_strings[counter] = std::string(jumbled_chars, 5); 

更新:

好吧,這裏有一些建議。而不是將您的字符串存儲在數組中,而是使用std::vector

std::vector<std::string> possible_strings; 
std::string jumbled_chars; //This could be a char[] or char* or whatever 

我會留下來確定如何獲取字符串的所有排列組合作爲練習讀者。但是,說你要獲得jumbled_charswxyz,其中w-zjumbled_chars索引的順序:

std::string str = ""; 
str += jumbled_chars[w]; 
str += jumbled_chars[x]; 
str += jumbled_chars[y]; 
str += jumbled_chars[z]; 

possible_strings.push_back(str); 
+0

cppreference.com更易於閱讀。 SGI STL文檔幾乎和ISO規範本身一樣冗長。 – moshbear

+2

每個人都有自己的:) – Anthony

+0

@moshbear:在某些時候它也幾乎是正確的。 – sehe

7
#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
     string theString = ""; 
     char a = 'a'; 
     char b = 'b'; 
     const char* c = "cdefghijklmnopqrstuvwxyz"; 

     theString += a; 
     theString += b; 
     theString += c; 

     cout << theString; 
     return 0; 
} 

打印出整個字母表。

相關問題