首页 > 解决方案 > 如何从 C++ 中的字符串返回子字符串?

问题描述

我需要在 C++ 中实现类似 python 的切片方法。如果他们问我:

  Slice("Hello World!",1)     output = "ello World!"
  Slice("Hello World!",0,5)   output = "Hello"
  Slice("Hello World!",0,-1)  output = "Hello World"
  Slice("Hello World!",3,-2)  output = "lo Worl"
  Slice("Hello World!",-5,-2) output = "orl"
  Slice("Hello World!",14)    output = "  "

如果我的约束是这样的,我将如何实现这个类似切片的方法

到目前为止,我已经尝试创建一个 forloop。我尝试创建一个空字符串并尝试附加所需的索引,但我不明白如何。

标签: c++arraysstring

解决方案


使用std::string::substr()方法,例如:

std::string Slice(const std::string &str, ssize_t start, ssize_t end)
{
    return str.substr(start, end-start);
}

如果你不能使用substr()(出于某种荒谬的原因),那么你可以使用更像这样的东西:

std::string Slice(const std::string &str, ssize_t start, ssize_t end)
{
    if (start >= str.length())
        return std::string();

    if (end > str.length())
        end = str.length();

    return std::string(str.c_str() + start, end - start);
}

推荐阅读