例如,如果我有
string x = "dog:cat";
我想提取冒号后面的所有内容,并返回cat。怎么做呢?
试试这个:
x.substr(x.find(":") + 1);
find
返回 npos
的边缘情况。并不保证 npos + 1
等于 0(请参见 https://dev59.com/v4Tba4cB1Zd3GeqP4VP5)。 - galsh83我知道已经很晚了,但我无法评论被接受的答案。如果您在find
函数中仅使用单个字符,请改用''
而不是""
。
正如Clang-Tidy所说:字符字面量重载更高效。
因此
x.substr(x.find(':') + 1)
来自rcs的被接受答案有待改进。我没有足够的声望,因此无法对答案进行评论。
std::string x = "dog:cat";
std::string substr;
auto npos = x.find(":");
if (npos != std::string::npos)
substr = x.substr(npos + 1);
if (!substr.empty())
; // Found substring;
很多程序员由于没有执行适当的错误检查而犯错。该字符串具有操作者感兴趣的哨兵,但如果pos > size(),则会抛出std::out_of_range异常。
basic_string substr( size_type pos = 0, size_type count = npos ) const;
#include <iostream>
#include <string>
int main(){
std::string x = "dog:cat";
//prints cat
std::cout << x.substr(x.find(":") + 1) << '\n';
}
#include <iostream>
#include <string>
std::string get_right_of_delim(std::string const& str, std::string const& delim){
return str.substr(str.find(delim) + delim.size());
}
int main(){
//prints cat
std::cout << get_right_of_delim("dog::cat","::") << '\n';
}
类似于这样的内容:
string x = "dog:cat";
int i = x.find_first_of(":");
string cat = x.substr(i+1);
Try this:
string x="dog:cat";
int pos = x.find(":");
string sub = x.substr (pos+1);
cout << sub;
#include <string>
#include <iostream>
std::string process(std::string const& s)
{
std::string::size_type pos = s.find(':');
if (pos!= std::string::npos)
{
return s.substr(pos+1,s.length());
}
else
{
return s;
}
}
int main()
{
std::string s = process("dog:cat");
std::cout << s;
}
size_t pos = x.find(":"); // 在字符串中找到 ":" 的位置
string str3 = str.substr (pos);
试试这个..
std::stringstream x("dog:cat");
std::string segment;
std::vector<std::string> seglist;
while(std::getline(x, segment, ':'))
{
seglist.push_back(segment);
}