开发者

how get integer only and remove all string in C# [duplicate]

This question already has answers here: 开发者_如何学JAVA return only Digits 0-9 from a String (8 answers) Closed 3 years ago.

How can I remove the strings and get only integers?

I have a string ( 01 - ABCDEFG )

i need to get (01) only


input = Regex.Replace(input, "[^0-9]+", string.Empty);


There is four different ways to do it (well probably more but I've selected these).

#1: Regex from Bala R

string output = Regex.Replace(input, "[^0-9]+", string.Empty);

#2: Regex from Donut and agent-j

string output = Regex.Match(input, @"\d+").Value;

#3: Linq

string output = new string(input.ToCharArray().Where(c => char.IsDigit(c)).ToArray());

#4: Substring, for this to work the dash has to be in the string between the digits and the text.

string output = input.Substring(0, input.IndexOf("-")).Replace(" ", "");

With these inputs:

string input1 = "01 - ABCDEFG";
string input2 = "01 - ABCDEFG123";

For 1 and 2 the results would be:

output1 = "01";
output2 = "01123";

For 3 and 4 the results would be:

output1 = "01";
output2 = "01";

If the expected result is to get all the digits in the string, use #1 or #2, but if the expected result is to only get the digits before the dash, use #3 or #4.

With string as short as this #1 and #2 are about equal in speed and likewise for #3 and #4, but if there is a lot of iterations or the strings are four times longer or more #2 is faster than #1 and #4 is faster than #3.

Note: If the parentheses is included in the strings #4 has to be modifyed to this, but that wont make it much slower:

string output = input.Substring(0, input.IndexOf("-")).Replace(" ", "").Replace("(", "");


try this:

Convert.ToInt32(string.Join(null, System.Text.RegularExpressions.Regex.Split(s, "[^\\d]")))

it returns integer value 1.


string snum = System.Text.RegularExpression.Regex.Match(s, "\d+").Value;
int num;
if (!int.TryParse(snum, out num))
  throw new Exception();


You should use Regular Expressions -- they're a pretty powerful way to match strings of text against certain patterns, and this is a great scenario in which to use them.

The pattern "\d+" will match a sequence of 1 or more digits. A simple method that uses this pattern to extract all numbers from a string is as follows:

public static List<int> ExtractInts(string input)
{
   return Regex.Matches(input, @"\d+")
      .Cast<Match>()
      .Select(x => Convert.ToInt32(x.Value))
      .ToList();
}

So you could use it like this:

List<int> result = ExtractInts("( 01 - ABCDEFG )");

For some more detailed info on Regular Expressions, see this page (MSDN) or this page (helpful "cheat sheet").


Check out this blog post: http://weblogs.asp.net/sushilasb/archive/2006/08/03/How-to-extract-numbers-from-string.aspx

A simple program that extracts the number from the String using a regular expression.

class Program
    {
    static void Main(string[] args)
    {
      Console.WriteLine(ExtractNumbers("( 01 - ABCDEFG )"));    // 01
      Console.ReadLine();
    }

    static string ExtractNumbers(string expr)
    {
        return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
    }
}

Hope this helps!


Get All Numbers from string

string str = "01567438absdg34590";
            string result = "";

             result = Regex.Replace(str, @"[^\d]", "");

            Console.WriteLine(result);
            Console.Read();

Output: 0156743834590


Response.Write(Convert.ToDecimal(string.Join(null, System.Text.RegularExpressions.Regex.Split(TextBox1.Text, "[^\\d .]"))));

This is for both int and decimal numbers.


Try this:

string XYZ = string.Join(null, System.Text.RegularExpressions.Regex.Split(“XYZ  77”, “[^\d]”));


You can also using this way to get your appropriate answer..

string sentence = "10 cats, 20 dogs, 40 fish and 1 programmer";
 string[] digits= Regex.Split(sentence, @"\D+");
             foreach (string value in digits)
             {
                 int number;
                 if (int.TryParse(value, out number))
                 {
                     Debug.Log(value);
                 }
             }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜