开发者

Isolate int from string

开发者 https://www.devze.com 2023-01-15 13:00 出处:网络
I have a string which is a word, then =, then a number. e.g \"RefreshRate=75\" I want to get the i开发者_StackOverflownteger at the end and store it in an Int. The program uses this value which is

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

e.g

"RefreshRate=75"

I want to get the i开发者_StackOverflownteger 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


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.


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


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


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


One way is to use string.Split:

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


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.


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


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

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


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


 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

0

精彩评论

暂无评论...
验证码 换一张
取 消