Dav*_*rky 18 c++ python string
在python中,我能够切割部分字符串; 换句话说,只需在某个位置后打印字符.在C++中是否有相同的功能?
Python代码:
text= "Apple Pear Orange"
print text[6:]
Run Code Online (Sandbox Code Playgroud)
会打印: Pear Orange
who*_*oan 25
是的,这是substr方法:
basic_string substr( size_type pos = 0,
size_type count = npos ) const;
Run Code Online (Sandbox Code Playgroud)
返回子串[pos,pos + count].如果请求的子字符串超出字符串的结尾,或者如果count == npos,则返回的子字符串为[pos,size()).
#include <iostream>
#include <string>
int main(void) {
std::string text("Apple Pear Orange");
std::cout << text.substr(6) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
在C++中,最接近的等价物可能是string :: substr().例:
std::string str = "Something";
printf("%s", str.substr(4)); // -> "thing"
printf("%s", str.substr(4,3)); // -> "thi"
Run Code Online (Sandbox Code Playgroud)
(第一个参数是初始位置,第二个参数是切片的长度).第二个参数默认为字符串结尾(string :: npos).
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.
Run Code Online (Sandbox Code Playgroud)
请注意,与 python 不同,第一个不进行范围检查:您的输入字符串需要足够长。根据您对切片的最终用途,可能还有其他替代方案(例如直接使用迭代器范围而不是像我在这里所做的那样制作副本)。
看起来 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/
听起来你想要string::substr:
std::string text = "Apple Pear Orange";
std::cout << text.substr(6, std::string::npos) << std::endl; // "Pear Orange"
Run Code Online (Sandbox Code Playgroud)
这里string::npos与“直到字符串末尾”同义(也是默认的,但为了清楚起见我将其包括在内)。
| 归档时间: |
|
| 查看次数: |
16064 次 |
| 最近记录: |