Python 字符串切片的 C++ 等价物?

C++ equivalent of Python String Slice?

在 python 中,我能够对字符串的一部分进行切片;换句话说,只打印某个位置之后的字符。在 C++ 中是否有与此等效的内容?

Python代码:

text= "Apple Pear Orange"
print text[6:]

将打印:Pear Orange

听起来像你想要的string::substr:

std::string text = "Apple Pear Orange";
std::cout << text.substr(6, std::string::npos) << std::endl; // "Pear Orange"

此处 string::npos 与 "until the end of the string" 同义(也是默认设置,但为了清楚起见,我将其包括在内)。

您可以使用字符串 class:

std::string text = "Apple Pear Orange";
size_t pos = text.find('Pear');
std::string text = "Apple Pear Orange";
std::cout << std::string(text.begin() + 6, text.end()) << std::endl;  // No range checking at all.
std::cout << text.substr(6) << std::endl; // Throws an exception if string isn't long enough.

请注意,与 python 不同,第一个不进行范围检查:您的输入字符串需要足够长。根据您对切片的最终用途,可能还有其他选择(例如直接使用迭代器范围而不是像我在这里做的那样制作副本)。

是的,就是substr方法:

basic_string substr( size_type pos = 0,
                     size_type count = npos ) const;
    

Returns a substring [pos, pos+count). If the requested substring extends past the end of the string, or if count == npos, the returned substring is [pos, size()).

例子

#include <iostream>
#include <string>

int main(void) {
    std::string text("Apple Pear Orange");
    std::cout << text.substr(6) << std::endl;
    return 0;
}

See it run

在 C++ 中,最接近的等价物可能是 string::substr()。 示例:

std::string str = "Something";
printf("%s", str.substr(4)); // -> "thing"
printf("%s", str.substr(4,3)); // -> "thi"

(第一个参数为初始位置,第二个为切片的长度)。 第二个参数默认为字符串结尾 (string::npos).

看起来 C++20 将有范围 https://en.cppreference.com/w/cpp/ranges 旨在提供类似 python 的切片 http://ericniebler.com/2014/12/07/a-slice-of-python-in-c/ 所以我在等待它出现在我最喜欢的编译器中,同时使用 https://ericniebler.github.io/range-v3/

**第一个参数确定起始索引,第二个参数指定结束索引记住字符串的起始是从 0 **

string s="Apple";

string ans=s.substr(2);//ple

string ans1=s.substr(2,3)//pl