Print a string with only numeric values

Asked

Viewed 380 times

-1

I’m doing a show in console where the user enters some codes, and I want to print this code back to him just when he gives enter.

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

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

  • 1

    I believe that in this question you have the answer: https://answall.com/questions/123453/remover-characters- n%C3%A3o-num%C3%A9ricos-de-uma-string. Possible duplicate.

3 answers

1


Follow another alternative using Linq

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

I put in the .Net Fiddle for reference

0

Marcelo, here you had a similar case (Look at this response from Maniero).

In this case, the AP requested that if the character had been typed again, this repetition would also be ignored.

Following the same logic of this answer, your Cap 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 (number).

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

Another alternative, using Linq would be so:

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

These two examples already adapted are available for testing on . Net Fiddle, explores there.

-1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.