简体   繁体   English

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

[英]C++ selecting N characters from string

I have a String. 我有一个字符串。 Let it be string a = "abcde"; 让它成为string a = "abcde"; .

And I want to select only a few characters (Let me say from 1 to 3). 我想只选择几个字符(让我说从1到3)。

In python I would do it like a[1:3] . 在python中,我会像a[1:3]那样做。 But C++ doesn't allow me to do that. 但是C ++不允许我这样做。 It only allows for example: a[n] , not a[n:x]. 它只允许例如: a[n] ,而不是[n:x]。

Is there a way to select n characters from string in C++? 有没有办法在C ++中从字符串中选择n字符?

Or do I need to do it with erase() ? 或者我需要使用erase()吗?

You can use substr() : 你可以使用substr()

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

Notice that indexing starts at 0 . 请注意,索引从0开始。

If you want to shorten the string itself, you can indeed use erase() : 如果你想缩短字符串本身,你确实可以使用erase()

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

If you want to reassign the object you can write for example 例如,如果要重新分配对象,可以编写

std::string a = "abcde";

a = a.substr( 0, 3 );

However to select the characters there is no need to change the object itself. 但是,要选择字符,则无需更改对象本身。 Most member functions of class std::string accept two parameters: the initial position in a string and the number of characters to process. std::string大多数成员函数接受两个参数: std::string的初始位置和要处理的字符数。 Also you can use iterators to process selected characters as for example a.begin() , std::next( a.begin(), 3 ) . 您还可以使用迭代器来处理选定的字符,例如a.begin()std::next( a.begin(), 3 ) You can use iterators that specify a range in a string in many standard algorithms. 您可以使用在许多标准算法中指定字符串范围的迭代器。

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

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