Print a string with only numeric values [duplicate]

-1

I'm doing a program in console where the user types some codes, and I want to print that code back to him as soon as he enters.

But I wanted to print only the numbers values and ignore the non-numeric values of the string.

Does anyone know how I can do this? How do I get a variable with the example value a132sb26c33 and print and only 1322633 on the console?

    
asked by anonymous 17.05.2018 / 20:58

3 answers

1

There is another alternative using Linq

string dados = "a132sb26c33";
string resultado = new String(dados.Where(Char.IsDigit).ToArray());
Console.WriteLine(resultado);

I put it in .Net Fiddle for reference

    
17.05.2018 / 21:07
0

Marcelo, you've had a similar case here ( See this answer from Maniero ).

In this case, the AP asked that if the character was typed repeated, that repetition would be ignored as well.

Following the same logic of this answer, your case would look like this:

var texto = "Abcc111de12234";
var lista = new char[texto.Length];

for (int i = 0, j = 0; i < texto.Length; i++) 
    if (char.IsDigit(texto[i])) 
        lista[j++] = texto[i];

var saida = new string(lista);

Basically, logic is reading the input ( texto ) and traversing each character of that input, discarding what is not a digit.

At the end, the result is passed to the variable saida .

Alternatively, using Linq would look like this:

var saida2 = new string(texto.Where(c => char.IsDigit(c)).ToArray());

These two examples have already been adapted are available for testing on .Net Fiddle , explore there.

    
17.05.2018 / 21:07
-1
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
    if (!string.IsNullOrEmpty(value))
    {
    int i = int.Parse(value);
    Console.WriteLine("Number: {0}", i);
    }
}

link

    
17.05.2018 / 21:04