简体   繁体   English

需要帮助了解substr c ++

[英]Need Help on understanding substr c++

I'm very new to programming so please correct me if I'm wrong 我对编程很陌生,所以如果我写错了,请纠正我

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

If I have this code: 如果我有此代码:

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

I expect this output ab 我希望这个输出ab

But I only got the first letter as an output a 但我只得到了第一个字母作为输出

As @user657267 points out in the comments, std::string::substr takes two parameters: the starting position, and the length; 正如@ user657267在注释中指出的那样, std::string::substr具有两个参数:起始位置和长度; not the ending position. 不是结束位置。

Thus if you wish to get "ab" from "abcde", you need to have the following: 因此,如果您希望从“ abcde”中获取“ ab”,则需要具备以下条件:

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

Syntax: 句法:

string.substr(start position, length of the string);

so, try this, 所以,尝试一下

string strand2 = strand1.substr(0, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM