【问题标题】:How exactly does string slicing work in C++ (using string)?字符串切片在 C++ 中究竟是如何工作的(使用字符串)?
【发布时间】:2022-01-22 10:22:16
【问题描述】:

我有以下代码:

string str1 = "first string";
string str2(str1, 6, 6)

// Output: string
  • 第一个参数指向需要切片的变量
  • 第二个参数告诉起始索引(从1开始)
  • 第三个参数告诉你想从 str1 中取出多少个字符 - 基本上是结束索引

我了解以上所有内容。但是,当我遇到下面的代码块时,我很困惑。

为什么会这样?它没有 3 个参数。

string str3(str1.begin(), str1.begin() + 5); // Why no 3rd param ? 
// Output: first

同样在这里,第二个参数 直到 到第 5 个索引,而不是从 那里开始(就像在第一个示例中一样)。有人能解释一下黑白代码块 1 和 2 有什么不同吗?

谢谢。

【问题讨论】:

  • 两者都是不同的演员。 std::string 有多个 overloads
  • “演员”是什么意思?
  • ctor 是构造函数的简写。

标签: c++ string slice


【解决方案1】:

正如评论中提到的@Ch3steR,它们都是ctors(构造函数),并且那个特定的构造函数有两个参数。

  1. 参数是一个指向起始字符的“迭代器”
  2. 参数是一个指向结束字符的“迭代器”。

这里是 bbcnsoft 文档的链接:

a string of characters denoted by the start and end iterators

这是 cppreference 文档的链接:

Constructs the string with the contents of the range (first, last)

这是 cplusplus 文档的链接:

(7) range constructor

【讨论】:

  • @OlafDietsche 我的错!我在手机上看打字看错了,第二个参数是iterator to。我稍后会修复它。关于 bccnsoft.com,当然 cppreference.com 对于 c++ 文档最可靠,但我估计 cppreference.com 只会让他感到困惑,因为他的知识非常基础。而且我相信 cccnsoft.com 没有任何问题,我在很多时候都成功地参考过它。
猜你喜欢
  • 1970-01-01
  • 2020-11-27
  • 2012-07-16
  • 2020-05-26
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2018-05-05
相关资源
最近更新 更多