Find and extract a number from a string

前端 未结 29 3420
温柔的废话
温柔的废话 2020-11-22 03:19

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 =         


        
29条回答
  •  难免孤独
    2020-11-22 03:58

    Based on the last sample I created a method:

    private string GetNumberFromString(string sLongString, int iLimitNumbers)
    {
        string sReturn = "NA";
        int iNumbersCounter = 0;
        int iCharCounter = 0; 
    
        string sAlphaChars = string.Empty;
        string sNumbers = string.Empty;
        foreach (char str in sLongString)
        {
            if (char.IsDigit(str))
            {
                sNumbers += str.ToString();
                iNumbersCounter++;
                if (iNumbersCounter == iLimitNumbers)
                {
                    return sReturn = sNumbers;
                }
            }
            else
            {
                sAlphaChars += str.ToString();
                iCharCounter++;
                // reset the counter 
                iNumbersCounter = 0; 
            }
        }
        return sReturn;
    }
    

提交回复
热议问题