How to get number from a string - c#

I would like to get number from a string eg:
My123number gives 123
Similarly varchar(32) gives 32 etc
Thanks in Advance.

If there is going to be only one number buried in the string, and it is going to be an integer, then something like this:
int n;
string s = "My123Number";
if (int.TryParse (new string (s.Where (a => Char.IsDigit (a)).ToArray ()), out n)) {
Console.WriteLine ("The number is {0}", n);
}
To explain: s.Where (a => Char.IsDigit (a)).ToArray () extracts only the digits from the original string into an array of char. Then, new string converts that to a string and finally int.TryParse converts that to an integer.

you could go the regular expression way. which is normally faster than looping through the string
public int GetNumber(string text)
{
var exp = new Regex("(\d+)"); // find a sequence of digits could be \d+
var matches = exp.Matches(text);
if (matches.Count == 1) // if there's one number return that
{
int number = int.Parse(matches[0].Value);
return number
}
else if (matches.Count > 1)
throw new InvalidOperationException("only one number allowed");
else
return 0;
}

Loop through each char in the string and test it for being a number. remove all non-numbers and then you have a simple integer as a string. Then you can just use int.parse.
string numString;
foreach(char c in inputString)
if (Char.IsDigit(c)) numString += c;
int realNum = int.Parse(numString);

You could do something like this, then it will work with more then one number as well
public IEnumerable<string> GetNumbers(string indata)
{
MatchCollection matches = Regex.Matches(indata, #"\d+");
foreach (Match match in matches)
{
yield return match.Value;
}
}

First write a specification of what you mean by a "number" (integer? long? decimal? double?) and by "get a number from a string". Including all the cases you want to be able to handle (leading/trailing signs? culture-invariant thousands/decimal separators, culture-sensitive thousands/decimal separators, very large values, strings that don't contain a valid number, ...).
Then write some unit tests for each case you need to be able to handle.
Then code the method (should be easy - basically extract the numeric bit from the string, and try to parse it. Some of the answers provided so far will work for integers provided the string doesn't contain a value larger than Int32.MaxValue).

Related

How can I get all texts between two characters but with a chosen number?

So simply what I want:
Input: Hey "There" "Random"
And I would simply:
GetTextBetweenBrackets(string userinput, 2);
Then
output: Random
static string GetTextBetweenBrackets(string text, int number)
{
string Output = "";
string[] split = text.Split(' ');
Output = split[number].Split('"', '"')[1];
return Output;
}
That code works good but if the input is:
input: Hey "There random" "Love Cats"
GetTextBetweenBrackets(string userinput, 2);
output: Nothing
This seems to work for you (but you should take care of potential exceptions)
static string GetTextBetweenBrackets(string text, int number)
{
return text.Split('"').Skip(2*number-1).First();
}
Then
var result0 = GetTextBetweenBrackets("Hey \"There\" \"Random\"", 2); //Random
var result1 = GetTextBetweenBrackets("Hey \"There random\" \"Love Cats\"", 2); //Love Cats
Use of regular expressions to find a quote, get the text until the next quote which produces a match, then one can get the right match by indexing into it that result list.
static string GetTextBetweenBrackets(string text, int number)
{
return Regex.Matches(text, #"\x22([^\x22]+)\x22") // \x22 is the hex escape for "
.OfType<Match>()
.Select(mt => mt.Value)
.ToList()
[number - 1];
}
GetTextBetweenBrackets("Hey \"There random\" \"Love Cats\"", 2) returns "Love Cats"
A reason to use this is that if there are other texts between your quotes, this will still work. Ex GetTextBetweenBrackets("My \"Name\" is, well \"Earl\"", 2) will return "Earl" and work, while the other solutions will fail due to just focusing on the one type of sentence.

c# How do trim all non numeric character in a string

what is the faster way to trim all alphabet in a string that have alphabet prefix.
For example, input sting "ABC12345" , and i wish to havee 12345 as output only.
Thanks.
Please use "char.IsDigit", try this:
static void Main(string[] args)
{
var input = "ABC12345";
var numeric = new String(input.Where(char.IsDigit).ToArray());
Console.Read();
}
You can use Regular Expressions to trim an alphabetic prefix
var input = "ABC123";
var trimmed = Regex.Replace(input, #"^[A-Za-z]+", "");
// trimmed = "123"
The regular expression (second parameter) ^[A-Za-z]+ of the replace method does most of the work, it defines what you want to be replaced using the following rules:
The ^ character ensures a match only exists at the start of a string
The [A-Za-z] will match any uppercase or lowercase letters
The + means the upper or lowercase letters will be matched as many times in a row as possible
As this is the Replace method, the third parameter then replaces any matches with an empty string.
The other answers seem to answer what is the slowest way .. so if you really need the fastest way, then you can find the index of the first digit and get the substring:
string input = "ABC12345";
int i = 0;
while ( input[i] < '0' || input[i] > '9' ) i++;
string output = input.Substring(i);
The shortest way to get the value would probably be the VB Val method:
double value = Microsoft.VisualBasic.Conversion.Val("ABC12345"); // 12345.0
You would have to regular expression. It seems you are looking for only digits and not letters.
Sample:
string result =
System.Text.RegularExpressions.Regex.Replace("Your input string", #"\D+", string.Empty);

How to use Regex in c# for the following situation

I have a textbox in which when the user tries to enter a word the format should only begin with 'PHY' followed by 8 digit numbers.
For example,
The correct format is PHY00000000
In here the first three letters 'PHY' is constant and the next 8 digit numbers vary from 00000000 to 10000000.
How to get this format using regex condition? No other format should be supported.
If you want regular expression for values range from PHY00000000 to PHY10000000, you should use:
PHY[0-1]\d{7}
But I do not like this, as we are trying to interpret value of number using regular expression. I would use them to split this input and interpret it as a number with specified range (then you can easily change this valid range of numbers):
static bool Valid(string input)
{
const string Pattern = #"PHY(\d{8})";
const int Max = 10000000;
var match = Regex.Match(input, Pattern);
if (match.Success)
{
int value = int.Parse(match.Groups[1].Value);
if (value <= Max)
{
return true;
}
}
return false;
}
So you can take Pattern and Max from some configuration etc.
In order to take care of the requirements, the following regex expression will work:
const string match = "PHY(0\d{7}|1(0){7})";
You then can validate the input by a simple method:
bool ValidateInput(string input)
{
var regex = new Regex(match);
return regex.IsMatch(input);
}

How To Convert The String (X cm) To INT (X) X = Number

How To Convert The String (X LE) To INT (X)
X = Number
I used :
Convert.ToInt32(Form1.sendproductprice1)*Convert.ToInt32(Form1.sendamount));
Example :
Form1.sendproductprice1 = "25 LE";
Form1.sendamount = 5;
Then value must be 125
But I got Error "Input string was not in correct format"
Obviously, 25 LE can't be converted to integer like that. You have to separate the number from the text. In this case, you can use
var num = Form1.sendproductprice1.Split(' ')[0];
which basically takes your input, splits it by spaces and takes the first item from the result. Then this will work
Convert.ToInt32(num)*Convert.ToInt32(Form1.sendamount));
Code below should be work:
Convert.ToInt32(Form1.sendproductprice1.Split(' ')[0])*Convert.ToInt32(Form1.sendamount));
You can extract the number from the string with this code (it allows you to extract the number even if it's not at the beggining)
for (int i=0; i< Form1.sendproductprice1.Length; i++)
{
if (Char.IsDigit(Form1.sendproductprice1[i]))
number += Form1.sendproductprice1[i];
}
Then if you do Convert.ToInt32(number) it will work just fine
You could also use regular expressions.
You will first need to separate the characters from the string to be able to convert the number to integer type.
Convert.ToInt32(Form1.sendproductprice1)
Will throw an exception if the string has something other than integers.
In your case (in the example you provided) the string is as follows: "25 LE"
If the delimeter is always a space then its easy:
var test = "25 LE";
var splitted = test.Split(' ');
var digits = splitted[0]; //Will get you the digits only.
If you want to handle whitespace you can use a Regex as well to parse the input
string input = " 25 LE ";
Regex regex = new Regex("\\d+");
Match match = regex.Match(input);
if (match.Success)
{
int number = Convert.ToInt32(match.Value); // number contains 25
}

How do I determine if there are two or one numbers at the start of my string?

How can I determine what number (with an arbitrary number of digits) is at the start of a string?
Some possible strings:
1123|http://example.com
2|daas
Which should return 1123 and 2.
Use a regular expression:
using System.Text.RegularExpressions;
str = "35|http:\/\/v10.lscache3.c.youtube.com\/videoplayback...";
Regex r = new Regex(#"^[0-9]{1,2}");
Match m = r.Match(str);
if(m.Success) {
Console.WriteLine("Matched: " + m.Value);
} else {
Console.WriteLine("No match");
}
will capture 1-2 digits at the beginning of the string.
You can use LINQ:
string s = "35|...";
int result = int.Parse(new string(s.TakeWhile(char.IsDigit).ToArray()));
or (if the number is always followed by a |) good ol' string manipulation:
string s = "35|...";
int result = int.Parse(s.Substring(0, s.IndexOf('|')));
if you know that the number is always going to be 2 digits:
string str = "35|http:\/\/v10.lscache3.c.youtube.com\/videoplayback?...";
int result;
if (!int.TryParse(str.Substring(0, 2), out result)) {
int.TryParse(str.Substring(0, 1), out result)
}
// use the number
if you're not sure how long the number is, look at the .indexOf() approach by dtb. If you need something much more complex, only then consider using regex.
You can get the two first characters and convert to int.
var s = "a35|...";
short result = 0;
bool isNum = Int16.TryParse(s.Substring(0, 2), out result);

Categories