How to extract all digits from a string in C#

3 Answers

0 votes
using System;

public class Program {

    // Function that extracts all digits from a string
    public static string extractDigits(string s) {
        string digits = "";
        foreach (char ch in s) {
            if (Char.IsDigit(ch)) {
                digits += ch;
            }
        }
        
        return digits;
    }

    public static void Main() {
        string s = "abc 9836 xy%^(s 21 * 9 ppp 100";

        Console.WriteLine(extractDigits(s));  // 9836219100
    }
}


/*
run:

9836219100

*/

 



answered Dec 16, 2020 by avibootz
edited Sep 16 by avibootz
0 votes
using System;
using System.Linq;

public class Program {

    public static string extract_digits(string s) {
        return new string(s.Where(Char.IsDigit).ToArray());
    }

    public static void Main() {
        string s = "abc 9836 xy%^(s 21 * 9 ppp 100";

        Console.WriteLine(extract_digits(s));   // 9836219100
    }
}


/*
run:

9836219100

*/

 



answered Dec 16, 2020 by avibootz
edited Sep 16 by avibootz
0 votes
using System;
using System.Text;
using System.Text.RegularExpressions;

public class Program {

    public static string extract_digits(string s) {
        StringBuilder sb = new StringBuilder();
        
        foreach (Match m in Regex.Matches(s, @"\d")) {
                sb.Append(m);
        }
        
        return sb.ToString();
    }

    public static void Main() {
        string s = "abc 9836 xy%^(s 21 * 9 ppp 100";

        Console.WriteLine(extract_digits(s));   // 9836219100
    }
}


/*
run:

9836219100

*/

 



answered Sep 16 by avibootz
...