C++ Extract Number from the Middle of a String

C++ Extract number from the middle of a string

updated for C++11

(important note for compiler regex support: for gcc. you need version 4.9 or later. i tested this on g++ version 4.9[1], and 9.2. cppreference.com has in browser compiler that i used.)

Thanks to user @2b-t who found a bug in the c++11 code!

Here is the C++11 code:

#include <iostream>
#include <string>
#include <regex>

using std::cout;
using std::endl;

int main() {
std::string input = "Example_45-3";
std::string output = std::regex_replace(
input,
std::regex("[^0-9]*([0-9]+).*"),
std::string("$1")
);
cout << input << endl;
cout << output << endl;
}

boost solution that only requires C++98

Minimal implementation example that works on many strings (not just strings of the form "text_45-text":

#include <iostream>
#include <string>
using namespace std;
#include <boost/regex.hpp>

int main() {
string input = "Example_45-3";
string output = boost::regex_replace(
input,
boost::regex("[^0-9]*([0-9]+).*"),
string("\\1")
);
cout << input << endl;
cout << output << endl;
}

console output:

Example_45-3
45

Other example strings that this would work on:

  • "asdfasdf 45 sdfsdf"
  • "X = 45, sdfsdf"

For this example I used g++ on Linux with #include <boost/regex.hpp> and -lboost_regex. You could also use C++11x regex.

Feel free to edit my solution if you have a better regex.


Commentary:

If there aren't performance constraints, using Regex is ideal for this sort of thing because you aren't reinventing the wheel (by writing a bunch of string parsing code which takes time to write/test-fully).

Additionally if/when your strings become more complex or have more varied patterns regex easily accommodates the complexity. (The question's example pattern is easy enough. But often times a more complex pattern would take 10-100+ lines of code when a one line regex would do the same.)


[1]

[1]
Apparently full support for C++11 <regex> was implemented and released for g++ version 4.9.x and on Jun 26, 2015. Hat tip to SO questions #1 and #2 for figuring out the compiler version needing to be 4.9.x.

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
long val = strtol(p, &p, 10); // Read number
printf("%ld\n", val); // and print it.
} else {
// Otherwise, move on to the next character.
p++;
}
}

Link to ideone.

Find and extract a number from a string

go through the string and use Char.IsDigit

string a = "str123";
string b = string.Empty;
int val;

for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}

if (b.Length>0)
val = int.Parse(b);

How to convert a part of string into integer?

Another way: You could replace non-digits with spaces so as to use stringstring extraction of the remaining integers directly:

std::string x = "15a16a17";
for (char &c : x)
{
if (!isdigit(c))
c = ' ';
}

int v;
std::stringstream ss(x);
while (ss >> v)
std::cout << v << "\n";

Output:

15
16
17

how to extract a number from string in c++ [duplicate]

You can use atoi and isdigit:

// Example string
std::string str = "this is my id 4321.";

// For atoi, the input string has to start with a digit, so lets search for the first digit
size_t i = 0;
for ( ; i < str.length(); i++ ){ if ( isdigit(str[i]) ) break; }

// remove the first chars, which aren't digits
str = str.substr(i, str.length() - i );

// convert the remaining text to an integer
int id = atoi(str.c_str());

// print the result
std::cout << id << std::endl;

Get a part of an integer in C

Getting a single digit as an int can be done mathematically:

int num = 897;
int dig1 = (num / 1 ) % 10;
int dig2 = (num / 10 ) % 10;
int dig3 = (num / 100 ) % 10;

Division by one on the first line is only for illustration of the concept: you divide by n-th power of ten, starting with 100 = 1.

C++ - extract numbers from a string

A job for stringstreams, see it live: http://ideone.com/e8GjMg

#include <sstream>
#include <iostream>

int main()
{
std::istringstream iss(" abcd 1234 -6242 1212");

std::string s;
int a, b, c;

iss >> s >> a >> b >> c;

std::cout << s << " " << a << " " << b << " " << c << std::endl;
}

Prints

abcd 1234 -6242 1212

C-Language: How to get number from string via sscanf?

A combination of digit filtering and sscanf() should work.

int GetNumber(const char *str) {
while (!(*str >= '0' && *str <= '9') && (*str != '-') && (*str != '+')) str++;
int number;
if (sscanf(str, "%d", &number) == 1) {
return number;
}
// No int found
return -1;
}

Additional work needed for numbers that overflow.

A slower, but pedantic method follows

int GetNumber2(const char *str) {
while (*str) {
int number;
if (sscanf(str, "%d", &number) == 1) {
return number;
}
str++;
}
// No int found
return -1;
}


Related Topics



Leave a reply



Submit