2

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

10 Answers 10

8

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.

Sign up to request clarification or add additional context in comments.

Comments

6
int i=Convert.ToInt32(st.Substring(st.IndexOf('=')+1))

Comments

5

If you are sure the format is word=value and is not variant, then this should work for you.

int value = int.Parse(line.Split('=').Last());

Edit: To deal with your hurts hertz problem

int value = int.Parse(line.Split('=').Last().Replace("Hz", ""));

Comments

4

How about:

    static int GetIntAfterEqual(string containsIntAfterEqual)
    {
        if(containsIntAfterEqual==null)
            throw new ArgumentNullException("containsIntAfterEqual");

        string[] splits = containsIntAfterEqual.Split('=');
        if (splits.Length == 2)
            return int.Parse(splits[1]);
        else
            throw new FormatException(containsIntAfterEqual);
    }

UPDATE: You said it could be "entryname=25hz". This should work for both cases:

    static int GetIntAfterEqual(string containsIntAfterEqual)
    {
        if(containsIntAfterEqual==null)
            throw new ArgumentNullException();

        Match match = Regex.Match(containsIntAfterEqual, @"[\d\w]+=([\d]+)\w*");
        if(match.Success)
            return int.Parse(match.Groups[1].Value);
        else
            throw new FormatException(containsIntAfterEqual);
    }

2 Comments

Hi, thanks for that....I had over looked smt :s 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
then in the place of this: ` return int.Parse(splits[1]);` put this: return int.Parse(splits[1].Replace("Hz", ""); and that will remove the Hz from the end. Also, you'll need to fix the if statement
2

One way is to use string.Split:

int.Parse(s.Split("=")[1])

Comments

2

If you confirm about your text format in word, Then you can use this

var word="RefreshRate = 756numHZ";
         int n;
         int.TryParse(word.tolower().Replace("refreshrate","").Replace("=", "").Replace("numhz", "").Trim(), out n);

This will also handle case of blank space in your text.

Comments

1
var line = "RefreshRate=75";
int number = int.Parse(line.Split('=')[1]);

Comments

0

You can do something along these lines, assuming that yourString contains the text RefreshRate=75.

int.Parse(yourString.Substring(yourString.IndexOf("=")+1));

1 Comment

Hi, thanks for that....I had over looked smt :s 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
0

In case you don't want to deal with or checking for "RefreshRate=" or "RefreshRate==" or "RefreshRate=Foobar" You can do the following

public static class IntParseExtension
    {
        public static bool TryParseInt(this string s, out int i)
        {
            i = 0;     
            bool retVal = false;
            int index;
            string sNumber;
            index = s.IndexOf("=");
            if (index > -1)
            {
                sNumber = s.Substring(index + 1);
                if (sNumber.Length > 0)
                    retVal = int.TryParse(sNumber, out i);
            }
            return retVal;
        }
    }

1 Comment

hi mate, thanks for this, i made an error though, its actually "RefreshRate=numHz"...i.e "RefreshRate=65Hz", sry for the mistake, can you offer me further advice please?
-3
 class Program
{
    static void Main(string[] args)
    {
        int j = 0 ;
        bool flag = false;
        string s = "myage = 400";

        char[]c = s.ToCharArray();
        for (int i = 0; i <= s.Length -1; i++)
        {
            if ((c[i] > '0') && (c[i] < '9'))
            {
                flag = true;
            }
            if (flag)
            {
                c[j++] = c[i];
            }
        }
        //for (; j < s.Length - 1; j++)
        //{
            c[j] = '\0';

        s = new string(c,0,j);
        int num = int.Parse(s);
        Console.WriteLine("{0}",num);
        Console.ReadKey();
    }

i don't know if there's a better solution ... this one works

3 Comments

TryParseInt? Where do you see that method?
And how are you handling peeling "100" off from "foo=100"
i didnt see the full Q this one works for cases where after = you have lot of spaces and staff ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.