Réponses:
Il y a plusieurs façons, mais cela devrait faire (je ne sais pas comment cela fonctionne avec de très grosses chaînes):
private static string GetNumbers(string input)
{
return new string(input.Where(c => char.IsDigit(c)).ToArray());
}
IsDigitplutôt que IsNumber: "Cette méthode [ IsNumber] détermine si a Charappartient à une catégorie Unicode numérique. En plus d'inclure des chiffres, les nombres incluent des caractères, des fractions, des indices, des exposants, des chiffres romains, des numérateurs de devises et des nombres encerclés. Cette méthode contraste avec la IsDigitméthode, qui détermine si a Charest un chiffre de base à 10. " msdn.microsoft.com/en-us/library/yk2b3t2y.aspx
input.Where(c => char.IsDigit(c) || char.IsWhiteSpace(c))
return new string(input.Where(char.IsDigit).ToArray());. Je le rend juste plus lisible
Se sent comme un bon ajustement pour une expression régulière.
var s = "40,595 p.a.";
var stripped = Regex.Replace(s, "[^0-9]", "");
"[^0-9]"peut être remplacé par @"\D"mais j'aime la lisibilité de [^0-9].
Une méthode d'extension sera une meilleure approche:
public static string GetNumbers(this string text)
{
text = text ?? string.Empty;
return new string(text.Where(p => char.IsDigit(p)).ToArray());
}
if (text == null) return string.Empty;plus text = text ?? string.Empty;. De cette façon, nous ne diminuons pas les performances.
Utilisez une expression régulière qui ne capture que 0-9 et rejette le reste. Une expression régulière est une opération qui coûtera cher la première fois. Ou faites quelque chose comme ça:
var sb = new StringBuilder();
var goodChars = "0123456789".ToCharArray();
var input = "40,595";
foreach(var c in input)
{
if(goodChars.IndexOf(c) >= 0)
sb.Append(c);
}
var output = sb.ToString();
Quelque chose comme ça je pense, je n'ai pas compilé cependant ..
LINQ est, comme l'a dit Fredrik, également une option
Une autre option ...
private static string RemoveNonNumberDigitsAndCharacters(string text)
{
var numericChars = "0123456789,.".ToCharArray();
return new String(text.Where(c => numericChars.Any(n => n == c)).ToArray());
}
public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");
Eh bien, vous savez quels sont les chiffres: 0123456789, non? Parcourez votre chaîne caractère par caractère; si le caractère est un chiffre, placez-le à la fin d'une chaîne temporaire, sinon ignorez. Il peut y avoir d'autres méthodes d'assistance disponibles pour les chaînes C #, mais c'est une approche générique qui fonctionne partout.
Voici le code utilisant des expressions régulières:
string str = "40,595 p.a.";
StringBuilder convert = new StringBuilder();
string pattern = @"\d+";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(str);
foreach (Match match in matches)
{
convert.Append(match.Groups[0].ToString());
}
int value = Convert.ToInt32(convert.ToString());
La réponse acceptée est excellente, mais elle ne prend pas en compte les valeurs NULL, ce qui la rend inutilisable dans la plupart des scénarios.
Cela m'a poussé à utiliser ces méthodes d'aide à la place. Le premier répond à l'OP, tandis que les autres peuvent être utiles pour ceux qui veulent effectuer le contraire:
/// <summary>
/// Strips out non-numeric characters in string, returning only digits
/// ref.: /programming/3977497/stripping-out-non-numeric-characters-in-string
/// </summary>
/// <param name="input">the input string</param>
/// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
/// <returns>the input string numeric part: for example, if input is "XYZ1234A5U6" it will return "123456"</returns>
public static string GetNumbers(string input, bool throwExceptionIfNull = false)
{
return (input == null && !throwExceptionIfNull)
? input
: new string(input.Where(c => char.IsDigit(c)).ToArray());
}
/// <summary>
/// Strips out numeric and special characters in string, returning only letters
/// </summary>
/// <param name="input">the input string</param>
/// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
/// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZAU"</returns>
public static string GetLetters(string input, bool throwExceptionIfNull = false)
{
return (input == null && !throwExceptionIfNull)
? input
: new string(input.Where(c => char.IsLetter(c)).ToArray());
}
/// <summary>
/// Strips out any non-numeric/non-digit character in string, returning only letters and numbers
/// </summary>
/// <param name="input">the input string</param>
/// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
/// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZ1234A5U6"</returns>
public static string GetLettersAndNumbers(string input, bool throwExceptionIfNull = false)
{
return (input == null && !throwExceptionIfNull)
? input
: new string(input.Where(c => char.IsLetterOrDigit(c)).ToArray());
}
Pour plus d'informations, lisez cet article sur mon blog.
var output = new string(input.Where(char.IsNumber).ToArray());