簡體   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