【问题标题】:function to select combinations of characters from a string in c++用于从 C++ 中的字符串中选择字符组合的函数
【发布时间】:2015-02-27 14:23:07
【问题描述】:

所以这是我的问题:

我需要一个函数,给定一个随机长度的字符串“qwer”,可以选择从 1 到字符串长度的所有可能的字符序列并将其放入一个数组中。 对不起,这很难解释,但我认为举个例子应该更容易理解。所以如果我有字符串“qwer”,我想要一个函数来创建一个包含以下条目的数组:

qwer qwe 韦尔 qwr qer qw q qr 我们 写 呃 q w e r

请注意,在具有多个字符的项目中,字符的顺序必须尊重原始字符串的顺序(例如,我想要项目 qwe,但我不想要 idem ewq)。因此,这不仅仅是排列问题,而是尊重原始顺序的排列问题。

另外,正如我在开头所说,理想情况下,该函数应该能够处理任意长度的字符串。

你知道这样的功能是否存在吗? 或者您对如何创建它有任何想法?我有点卡住了..

【问题讨论】:

  • “这是我的问题” ib4 这是我的作业
  • q w e r qq qw qe qr wq ww we wr eq ew ee er rq rw re rr qqq qqw etc. 256 个可能的序列!

标签: c++ string character combinations


【解决方案1】:

正如 Bathsheba 所说,我们需要用位替换字符。然后迭代比特可能产生的所有可能值。我的示例仅适用于长度小于 31 的短字符串。如果您需要更多,请使用 std::bitset 容器。

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> f(const std::string & str)
{
    const int length = str.length();
    const int bits = 1 << length;

    std::vector<std::string> result;
    for (int i = 1; i < bits; ++i)
    {
        std::string combined_string;
        for (int bit = 0; bit < length; ++bit)
        {
            if (i & (1<< bit))
            {
                combined_string += str[bit];
            }
        }
        result.push_back(combined_string);
    }

    return result;
}

void main()
{
    for (auto str : f("qwer"))
    {
       std::cout << str << " ";
    }
    std::cout << std::endl;
}

【讨论】:

    【解决方案2】:

    这是一种方法。

    1. 将 0 或 1 与每个字母相关联。 0 表示不包含,1 表示包含。
    2. 编写函数将(二进制)数字映射到字符串。例如,0111 将映射到 wer。
    3. 构建代码以计算从 0 到停止条件(1111,即在您的情况下为 15)的整数。将这些整数映射为二进制,然后应用 (2)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2023-04-04
      • 2022-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多