Mar*_*cel 36 c# string parsing integer tryparse
我只想知道,String变量是否包含可解析的正整数值.我现在不想解析这个值.
目前我在做:
int parsedId;
if (
(String.IsNullOrEmpty(myStringVariable) ||
(!uint.TryParse(myStringVariable, out parsedId))
)
{//..show error message}
Run Code Online (Sandbox Code Playgroud)
这很难看 - 如何更简洁?
注意:我知道扩展方法,但我想知道是否有内置的东西.
DGi*_*bbs 60
你可以使用char.IsDigit:
bool isIntString = "your string".All(char.IsDigit)
Run Code Online (Sandbox Code Playgroud)
true如果字符串是数字,则返回
bool containsInt = "your string".Any(char.IsDigit)
Run Code Online (Sandbox Code Playgroud)
true如果字符串包含数字,则返回
dtb*_*dtb 26
假设您要检查字符串中的所有字符是否为数字,您可以使用Enumerable.All扩展方法和Char.IsDigit方法,如下所示:
bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit);
Run Code Online (Sandbox Code Playgroud)
pan*_*ako 10
也许这可以帮助
string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));
Run Code Online (Sandbox Code Playgroud)
来自msdn的答复。
您可以检查字符串是否仅包含数字:
Regex.IsMatch(myStringVariable, @"^-?\d+$")
Run Code Online (Sandbox Code Playgroud)
但是数字可能大于Int32.MaxValue或小于Int32.MinValue- 你应该牢记这一点.
另一种选择 - 创建扩展方法并在那里移动丑陋的代码:
public static bool IsInteger(this string s)
{
if (String.IsNullOrEmpty(s))
return false;
int i;
return Int32.TryParse(s, out i);
}
Run Code Online (Sandbox Code Playgroud)
这将使您的代码更干净:
if (myStringVariable.IsInteger())
// ...
Run Code Online (Sandbox Code Playgroud)