C++ How to get substring after a character?

2020-05-23 06:13发布

For example, if I have

string x = "dog:cat";

and I want to extract everything after the ":", and return cat. What would be the way to go about doing this?

9条回答
爷的心禁止访问
2楼-- · 2020-05-23 06:50

something like this:

string x = "dog:cat";
int i = x.find_first_of(":");
string cat = x.substr(i+1);
查看更多
可以哭但决不认输i
3楼-- · 2020-05-23 06:52

Try this:

x.substr(x.find(":") + 1); 
查看更多
看我几分像从前
4楼-- · 2020-05-23 06:53

Try this one..

std::stringstream x("dog:cat");
std::string segment;
std::vector<std::string> seglist;

while(std::getline(x, segment, ':'))
{
   seglist.push_back(segment);
}
查看更多
劳资没心,怎么记你
5楼-- · 2020-05-23 06:59

What you can do is get the position of ':' from your string, then retrieve everything after that position using substring.

size_t pos = x.find(":"); // position of ":" in str

string str3 = str.substr (pos);

查看更多
啃猪蹄的小仙女
6楼-- · 2020-05-23 07:00
#include <iostream>
#include <string>

int main(){
  std::string x = "dog:cat";

  //prints cat
  std::cout << x.substr(x.find(":") + 1) << '\n';
}

Here is an implementation wrapped in a function that will work on a delimiter of any length:

#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';

}
查看更多
男人必须洒脱
7楼-- · 2020-05-23 07:02

I know it will be super late but I am not able to comment accepted answer. If you are using only a single character in find function use '' instead of "". As Clang-Tidy says The character literal overload is more efficient.

So x.substr(x.find(':') + 1)

查看更多
登录 后发表回答