2011-11-23 208 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; 
} 

打印出整个字母表。

相关问题