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"
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"
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);
}
}
I don't think there are any built-in string methods to do that. However you can tweak the code given in the below post and modify it to achieve what you want:
You can do it with Regular Expressions.
string myString = "USD3,000";
Regex reg = new Regex("[A-Za-z]");
myString = reg.Replace(myString, "");
string str = "ddd3,000.00ss";
string stripped = new Regex(@"(\d{1,3},(\d{3},)*\d{3}(\.\d{1,3})?|\d{1,3}(\.\d{3})?).*").Match(str).Value;
Console.WriteLine(stripped);
Output:
3,000.00ss
Should match decimal and integer number with or without thousand separators and with or without maximum of 3 decimal places.