gpt4 book ai didi

c++ - 需要帮助理解 substr c++

转载 作者:行者123 更新时间:2023-11-28 02:16:55 25 4
gpt4 key购买 nike

刚接触编程,如有错误请指正

strand1.substr(开始位置,结束位置)

如果我有这段代码:

int main()
{
string strand1 = "abcde";
int pos = 1;
string strand2 = strand1.substr(0, pos);
cout << strand2;
_getch();
return 0;
}

我期待这个输出ab

但我只得到第一个字母作为输出一个

最佳答案

正如@user657267 在评论中指出的那样,std::string::substr有两个参数:起始位置和长度; 不是结束位置。

因此,如果你想从“abcde”中得到“ab”,你需要具备以下条件:

std::string strand1 = "abcde";
auto strand2 = strand1.substr(0, 2);

关于c++ - 需要帮助理解 substr c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33770709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com