C++从字符串中选择N个字符

Urh*_*Urh 2 c++ substring substr

我有一个字符串.就这样吧string a = "abcde";.

我想只选择几个字符(让我说从1到3).

在python我会这样做a[1:3].但是C++不允许我这样做.它只允许例如:a[n],而不是[n:x].

有没有办法n从C++中的字符串中选择字符?

或者我需要这样做erase()吗?

Dan*_*_ds 8

你可以使用substr():

std::string a = "abcde";
std::string b = a.substr(0, 3);
Run Code Online (Sandbox Code Playgroud)

请注意,索引从0.

如果你想缩短字符串本身,你确实可以使用erase():

a.erase(3); // removes all characters starting at position 3 (fourth character)
            // until the end of the string
Run Code Online (Sandbox Code Playgroud)


Vla*_*cow 5

例如,如果要重新分配对象,可以编写

std::string a = "abcde";

a = a.substr( 0, 3 );
Run Code Online (Sandbox Code Playgroud)

但是,要选择字符,则无需更改对象本身.类的大多数成员函数std::string接受两个参数:字符串中的初始位置和要处理的字符数.您也可以使用迭代器处理选定的字符,例如a.begin(),std::next( a.begin(), 3 ).您可以使用在许多标准算法中指定字符串范围的迭代器.