2013-02-18 2 views
0

Existe-t-il un moyen d'ajuster une chaîne au premier chiffre numérique à gauche et à droite à l'aide des outils standard .NET? Ou je dois écrire ma propre fonction (pas difficile, mais je préfère utiliser des méthodes standard). J'ai besoin des sorties suivantes pour les entrées fournies:Ajuster au premier nombre

Input   Output 
----------------------- 
abc123def  123 
;'-2s;35(r  2s;35 
abc12de3f4g  12de3f4 

Répondre

4

Vous devez utiliser regular expressions

string TrimToDigits(string text) 
{ 
    var pattern = @"\d.*\d"; 
    var regex = new Regex(pattern); 

    Match m = regex.Match(text); // m is the first match 
    if (m.Success) 
    { 
     return m.Value; 
    } 

    return String.Empty; 
} 

Si vous voulez appeler cela comme vous le feriez normalement la méthode String.Trim(), vous pouvez créer comme un extension method.

static class StringExtensions 
{ 
    static string TrimToDigits(this string text) 
    { 
     // ... 
    } 
} 

Et alors vous pouvez l'appeler comme ceci:

var trimmedString = otherString.TrimToDigits(); 
+0

Ceci est une solution très élégante (mais pas la fonction Trim standard). Merci beaucoup. – Daniel

1

Non, il n'y a pas de construction intégrée. Vous devrez écrire votre propre méthode pour le faire.

0

Non, je ne pense pas qu'il y ait. Méthode cependant:

for (int i = 0; i < str.Length; i++) 
{ 
    if (char.IsDigit(str[i])) 
    { 
     break; 
    } 
    str = string.Substring(1); 
} 
for (int i = str.Length - 1; i > 0; i--) 
{ 
    if (char.IsDigit(str[i])) 
    { 
     break; 
    } 
    str = string.Substring(0, str.Length - 1); 
} 

Je pense que ça va fonctionner.

Questions connexes