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?
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?
Try this:
x.substr(x.find(":") + 1); std::string_view to avoid copying.find returning npos. It is not guaranteed that npos + 1 equals 0 (see stackoverflow.com/questions/26402961/…).The accepted answer from rcs can be improved. Don't have rep so I can't comment on the answer.
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; Not performing proper error checking trips up lots of programmers. The string has the sentinel the OP is interested but throws std::out_of_range if pos > size().
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'; } 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'; } #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; }