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

标签 c++ arrays string

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

最佳答案

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

关于c++ - 如何从 C++ 中的字符串返回子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680902/

相关文章:

c++ - 在编译时获取当前月份索引

javascript - Discord.js 中有没有办法取消固定所有已固定的消息?

string - Swift 字符串和 NSString 初始化器

c++ - 双插槽与单插槽内存模型?

C++/Qt - 编译问题 : syntax error : missing ';' before identifier - No idea

c++ - 在类中启动的第二个线程中的 OpenGL

javascript - ParseInt 数组中的元素为 int

c - 在 mcu 上的 malloc 之后需要一个 free()(即使数组/指针总是在使用中)?

c# - 插入存储在数据库中的字符串

java - 字符串比较时的错误结果