从字符串中给定结束索引的字符串复制子字符串

新手上路,请多包涵

如何从具有开始和结束索引的给定字符串中复制子字符串,或者给出字符串的开始索引和长度。

原文由 boom 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 406
2 个回答

std::stringstd::string::substr 将创建一个新的 std::string 从现有的给定起始索引和长度。在给定结束索引的情况下确定必要的长度应该是微不足道的。 (如果结束索引是包含而不是独占,则应格外小心以确保它是字符串的有效索引。)

如果您尝试从 C 样式字符串(以 NUL 结尾的 char 数组)创建子字符串,则可以使用 std::string(const char* s, size_t n) 构造函数。例如:

 const char* s = "hello world!";
size_t start = 3;
size_t end = 6; // Assume this is an exclusive bound.

std::string substring(s + start, end - start);

std::string::substr 不同, std::string(const char* s, size_t n) 构造函数可以读取输入字符串的末尾,因此在这种情况下,您还应该首先验证结束索引是否有效。

原文由 jamesdlin 发布,翻译遵循 CC BY-SA 4.0 许可协议

也许这不是一个理想的选择,而且有点不像 C++ 的风格,但至少它工作得很好。我的版本 SubString 接受 std::string 将在字符串下搜索起始索引和结束索引。子字符串将在 startend 索引之间返回。

     std::string SubString(const std::string& string, int beginIndex, int endIndex) {
        int size = (int)string.size();
        if (beginIndex < 0 || beginIndex > size - 1)
            return "-1"; // Index out of bounds
        if (endIndex < 0 || endIndex > size - 1)
            return "-1"; // Index out of bounds
        if (beginIndex > endIndex)
            return "-1"; // Begin index should not be bigger that end.

        std::string substr;
        for (int i = 0; i < size; i++)
            if (i >= beginIndex && i <= endIndex)
                substr += (char)string[i];
        return substr;
    }

原文由 Kenny 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题