【问题标题】:How to fill in an array with strings?如何用字符串填充数组?
【发布时间】:2020-05-26 14:06:25
【问题描述】:

我在自动填充特殊字符串数组时遇到问题。

字符串必须如下所示:"01""012" 等,直到到达"012...XYZ"

我曾想过制作一个像这样的“参考”字符串:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 以便能够浏览它并基于它创建其他字符串,但我认为有更简单的方法,我无法实现这个系统.

提前致谢!

【问题讨论】:

  • 你真的需要一个数组吗?您可以只使用 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 并知道“数组元素 5”只是该数组的索引 [0, 7]。
  • 注意:浏览参考字符串并创建子字符串相当容易...

标签: c++ arrays string


【解决方案1】:

只需浏览参考字符串并创建子字符串。为此,使用std::string::substr 相当有用。

很难找到更简单的解决方案。

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

std::vector<std::string> get_subs(const std::string &ref) {
    int n = ref.size();
    std::vector<std::string> vec;
    for (int i = 2; i <= n; ++i) {
        vec.emplace_back (ref.substr(0, i));
    }
    return vec;
}

int main () {
    std::string ref = "01234567";
    std::vector<std::string> res = get_subs (ref);
    for (std::string &s: res) {
        std::cout << s << " ";
    }
    std::cout << "\n";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    相关资源
    最近更新 更多