C++ How to get substring after a character?

78,175

Solution 1

Try this:

x.substr(x.find(":") + 1); 

Solution 2

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)

Solution 3

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;

Solution 4

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

}

Solution 5

something like this:

string x = "dog:cat";
int i = x.find_first_of(":");
string cat = x.substr(i+1);
Share:
78,175
SKLAK
Author by

SKLAK

Updated on August 03, 2020

Comments

  • SKLAK
    SKLAK almost 4 years

    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?

  • sjsam
    sjsam over 9 years
    Thinking of delims of any length is simply smart, so a +1
  • Brahmanand Choudhary
    Brahmanand Choudhary over 9 years
    I have executed this code it works ..tutorialspoint.com/compile_cpp_online.php
  • Spandyie
    Spandyie almost 5 years
    This is amazing !! <3
  • Kyle
    Kyle over 4 years
    This creates a copy, which may not be what you want. In C++17 you can use std::string_view to avoid copying.
  • galsh83
    galsh83 over 4 years
    As mentioned in some of the other answers, you should handle the edge case of find returning npos. It is not guaranteed that npos + 1 equals 0 (see stackoverflow.com/questions/26402961/…).
  • User123
    User123 about 4 years
    What if I had "cat:dog:parrot:horse" and I want to get just horse? (So the last one :)
  • Virtuall.Kingg
    Virtuall.Kingg about 2 years
    @rcs How should I do exactly same thing in C programming?