Search code examples
c#stringtexttrimming

Is there any method that truncates part of a string until the first number is encountered in C#?


I would like to know whether there is any method in C# that takes out all the content of a string until the first number is encountered. Example:

string myString = "USD3,000";
myString = SomeMethod(myString, [someparameters]);
myString -> "3,000"

Solution

  • Not inbuilt, but you could just use either a regex, or IndexOfAny:

    static void Main()
    {
        string myString = "USD3,000";
        var match = Regex.Match(myString, @"[0-9].*");
        if(match.Success)
        {
            Console.WriteLine(match.Value);
        }
    }
    

    or

    static readonly char[] numbers = "0123456789".ToCharArray();
    static void Main()
    {
        string myString = "USD3,000";
        int i = myString.IndexOfAny(numbers);
        if (i >= 0)
        {
            string s = myString.Substring(i);
            Console.WriteLine(s);
        }
    }