如何从C ++中的字符串返回子字符串?

时间:2019-04-14 23:21:08

标签: c++ arrays string

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

  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。我试图制作一个空字符串,并尝试附加所需的索引,但我不知道如何。

1 个答案:

答案 0 :(得分:3)

使用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);
}