繁体   English   中英

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

[英]C++ selecting N characters from string

我有一个字符串。 让它成为string a = "abcde";

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

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

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

或者我需要使用erase()吗?

你可以使用substr()

std::string a = "abcde";
std::string b = a.substr(0, 3);

请注意,索引从0开始。

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

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

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

std::string a = "abcde";

a = a.substr( 0, 3 );

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

暂无
暂无

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

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