Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolate int from string

Tags:

c#

I have a string which is a word, then =, then a number.

e.g

"RefreshRate=75"

I want to get the integer at the end and store it in an Int. The program uses this value which is stored in an ini file, I need to isolate this value as some other values calculations are based upon it.

How can this be done?

Thank you in advance

Ooooopsss:

Sorry guys, i made a blunder.

The string is actually in the format "RefreshRate=numHz"...i.e "RefreshRate=65Hz"...Im sure this would work, however I get "Incorrect input format error since its adding the Hz as well, and this is throwingthe exception :s

like image 426
brux Avatar asked Jul 02 '26 14:07

brux


1 Answers

It’s easy! Just use a regular expression!

var m = Regex.Match(input, @"=\s*(-?\d+)");
if (!m.Success)
    throw new InvalidOperationException(
        "The input string does not contain a number.");
return Convert.ToInt32(m.Groups[1].Value);

This extracts the first integer that follows a = in any string. Therefore, if your input string is "Frequency2=47Hz", it will return 47.

like image 154
Timwi Avatar answered Jul 05 '26 03:07

Timwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!