HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Find and extract a number from a string

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromextractandfindnumberstring

Problem

I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"


How can I do this?

Solution

go through the string and use Char.IsDigit

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

for (int i=0; i0)
    val = int.Parse(b);

Code Snippets

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);

Context

Stack Overflow Q#4734116, score: 108

Revisions (0)

No revisions yet.