问题
Using the .Net Compact Framework 2.0, how can I validate an integer (Int32.TryParse
is not supported on the Compact Framework)?
回答1:
What do you mean by "validate"? Do you mean parse without throwing?
static bool TryParse(string s, out int value)
{
try
{
value = int.Parse(s);
return true;
}
catch
{
value = 0;
return false;
}
}
回答2:
static bool TryParseImpl(string s, int start, ref int value)
{
if (start == s.Length) return false;
unchecked {
int i = start;
do {
int newvalue = value * 10 + '0' - s[i++];
if (value != newvalue / 10) { value = 0; return false; } // detect non-digits and overflow all at once
value = newvalue;
} while (i < s.Length);
if (start == 0) {
if (value == int.MinValue) { value = 0; return false; }
value = -value;
}
}
return true;
}
static bool TryParse(string s, out int value)
{
value = 0;
if (s == null) return false;
s = s.Trim();
if (s.Length == 0) return false;
return TryParseImpl(s, (s[0] == '-')? 1: 0, ref value);
}
Demo: http://ideone.com/PravA
回答3:
Had same problem. Try this:
static bool numParser(string s)
{
foreach (char c in s)
if (!char.IsNumber(c))
return false;
return true;
}
回答4:
public static bool IsInt(string s) {
bool isInt = true;
for (int i = 0; i < s.Length; i++) {
if (!char.IsDigit(s[i])) {
isInt = false;
break;
}
}
return isInt;
}
Example:
string int32s = "10240";
bool isInt = IsInt(int32s); // resolves true
Or:
string int32s = "1024a";
bool isInt = IsInt(int32s); // resolves false
回答5:
If your number is a string you may get the strings char array and check if Char.IsNumber
is true for every char.
Check if the first char is '-' to allow for negative numbers, if you need them and add a try/catch block to protect from numbers exceeding the range (int min / max value). If you don't have to deal with numbers approaching min/max consider setting a max length (maybe 6-7 digits) and simply check string.Length
instead.
If the chance you encounter only valid int
s and invalid ones are rare invalid operations you may stick with a simple try/catch block (see my comment to ctackes answer).
来源:https://stackoverflow.com/questions/6563968/c-sharp-integer-validation-compactframework