我怎样把许多字符放到一个字符串里?

How Can I Take Many Chars and Put Them Into One String

本文关键字:一个 字符串 许多 字符      更新时间:2023-10-16

我想我只是从来没有学过这个。我以前从来没有做过这个。我见过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];

我想做的是编写一个程序,它可以将一个单词分解成所有可能的排列。

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

打印出整个字母表

使用append功能或std::stringoperator+=过载。你应该仔细阅读STL文档。

如果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

我将把如何准确地获得字符串的所有排列留给读者作为练习。但是,假设您希望按照w, x, y, z的顺序获得jumbled_chars,其中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);
相关文章: