Try this simple method too:
string input = "ABC3454 ";
string output = string.Concat( input.Where( Char.IsDigit ) );
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi, I have a string consisting of alphabets and empty spaces, from which I have to extract only the number
Without using Regex is there a simple c# method I can use to extract ?
Eg: string input = "ABC3454 "
I need OUTPUT : 3454
Try this simple method too:
string input = "ABC3454 ";
string output = string.Concat( input.Where( Char.IsDigit ) );
One of the first Google links gives : How to find and extract a number from a string in C#?
Your sample shows letters followed by digits and you say you need all the digits. If your requirements are different, such as if there can be letters after the digits, then you need to say so.
Let us look at the String Class. I see a String.IndexOfAny Method. Just provide the ten digits for the chars to be found.
Try this simple function that will return the numbers from a string:
private string GetNumbers(String InputString)
{
String Result = "";
string Numbers = "0123456789";
int i = 0;
for (i = 0; i < InputString.Length; i++)
{
if(Numbers.Contains(InputString.ElementAt(i)))
{
Result += InputString.ElementAt(i);
}
}
return Result;
}
If this is for SQL-Server, you can create a function e.g.
CREATE FUNCTION dbo.udf_GetNumeric
(
@strAlphaNumeric VARCHAR(256)
)
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
GO
To create the function, create a new query, add the code above and execute it. Best done in SSMS (SQL-Server Management Studio)
And here I use it on a column that has alphanumeric values. ShipAddress is the original and ShipAddressNumbersOnly uses the function.