[c#] estrarre numeri da una stringa

martedì 11 settembre 2007 - 10.49

bejelit Profilo | Newbie

avendo una stringa con caratteri simboli e numeri

string var = "fr5hygd4-7c_";

vorrei estrarre solo i numeri 547

come posso fare?

AndreaKpr Profilo | Senior Member

Ciao, prova cosi :

string var = "a1d2g*ùèé*[gh3]4ionmas///5";
string Car = "";
string numero = "";


for (int I = 0; I < var.Length;I++)
{
Car = var.Substring(I,1);

try
{
decimal x_temp = Decimal.Parse(Car);
numero += x_temp;
}
catch
{
// il carattere non è un numero.
}

}

MessageBox.Show(numero);

munissor Profilo | Senior Member

Evita di utilizzare le eccezioni per il controllo di flusso..

Molto meglio usare char.IsDigit...

string var = "as234fdge4653qada";
foreach(char c in var)
{
if(char.IsDigit(c))
// è un numero
else
//non è un numero
}
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?

Dopo esserti registrato potrai chiedere
aiuto sul nostro Forum oppure aiutare gli altri

Consulta le Stanze disponibili.

Registrati ora !
Copyright © dotNetHell.it 2002-2024
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5