C++ 从字符串中选择 N 个字符
C++ selecting N characters from string
我有一个字符串。让它成为 string a = "abcde";
.
我只想 select 几个字符(让我说从 1 到 3)。
在 python 我会像 a[1:3]
那样做。
但是 C++ 不允许我这样做。它只允许例如:a[n]
,而不是 [n:x].
有没有办法从 C++ 中的字符串中 select 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 );
然而对于select字符,没有必要改变对象本身。 class std::string
的大多数成员函数接受两个参数:字符串中的初始位置和要处理的字符数。您也可以使用迭代器来处理 selected 字符,例如 a.begin()
、std::next( a.begin(), 3 )
。您可以在许多标准算法中使用指定字符串范围的迭代器。
我有一个字符串。让它成为 string a = "abcde";
.
我只想 select 几个字符(让我说从 1 到 3)。
在 python 我会像 a[1:3]
那样做。
但是 C++ 不允许我这样做。它只允许例如:a[n]
,而不是 [n:x].
有没有办法从 C++ 中的字符串中 select 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 );
然而对于select字符,没有必要改变对象本身。 class std::string
的大多数成员函数接受两个参数:字符串中的初始位置和要处理的字符数。您也可以使用迭代器来处理 selected 字符,例如 a.begin()
、std::next( a.begin(), 3 )
。您可以在许多标准算法中使用指定字符串范围的迭代器。