Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you search a std::string for a substring in C++?

Tags:

c++

string

I'm trying to parse a simple string in C++. I know the string contains some text with a colon, followed immediately by a space, then a number. I'd like to extract just the number part of the string. I can't just tokenize on the space (using sstream and <<) because the text in front of the colon may or may not have spaces in it.

Some example strings might be:

Total disk space: 9852465

Free disk space: 6243863

Sectors: 4095

I'd like to use the standard library, but if you have another solution you can post that too, since others with the same question might like to see different solutions.

like image 737
Bill the Lizard Avatar asked Dec 06 '08 21:12

Bill the Lizard


People also ask

How do you find the occurrence of a substring in a string C++?

Find indices of all occurrence of one string in other in C++ To solve this problem, we can use the substr() function in C++ STL. This function takes the initial position from where it will start checking, and the length of the substring, if that is the same as the sub_str, then returns the position.

How do I find a substring in a string?

The String class provides two accessor methods that return the position within the string of a specific character or substring: indexOf and lastIndexOf . The indexOf method searches forward from the beginning of the string, and lastIndexOf searches backward from the end of the string.

How do you find a specific letter in a string C?

The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search.


1 Answers

std::string strInput = "Total disk space: 9852465";
std::string strNumber = "0";
size_t iIndex = strInput.rfind(": ");
if(iIndex != std::string::npos && strInput.length() >= 2)
{
  strNumber = strInput.substr(iIndex + 2, strInput.length() - iIndex - 2)
}
like image 77
Brian R. Bondy Avatar answered Oct 21 '22 05:10

Brian R. Bondy