August 24, 2012

C#/LINQ - Split Number From Strings

Code to Split Number From Strings

/// <summary>
/// This Function used to spilt No from word
/// </summary>
/// <param name="strInput">Given String</param>
/// <returns>Expected No, If not found then returns -1</returns>
public Int64 SpiltNumberFromString(String strInput)
{
    string[] digits = Regex.Split(strInput, @"\D+", RegexOptions.Compiled);
    string numbers = string.Empty;
    foreach (string value in digits)
    {
        int number;
        if (int.TryParse(value, out number))
            numbers = numbers + number.ToString(CultureInfo.InvariantCulture);
    }
    return numbers.Length == 0 ? -1 : int.Parse(numbers);
}


LINQ Approach

/// <summary>
/// This Function used to spilt No from word
/// </summary>
/// <param name="strInput">Given String</param>
/// <returns>Expected No, If not found then returns -1</returns>
public Int64 SpiltNumberFromString(String strInput)
{
    int number = -1;
    string numberString = Regex.Split(strInput, @"\D+", RegexOptions.Compiled)
                            .Where(value => int.TryParse(value, out number))
                            .Aggregate(string.Empty, (current, value) => current + number.ToString(CultureInfo.InvariantCulture));
    return Int64.Parse(numberString);
}

No comments:

Post a Comment