检查字符串是否为数字 C#:]
Check a string if it was a number C# :]
所以我有一个名为 isNumber 的 bool Variabel。
bool isNumber(string Text)
{
bool Answer = true;
string Number = "1234567890";
bool ANumber = false;
for(int j = 0; j <Text.Length; j++)//loop for each char in string Text
{
for (int i = 0; i < Number.Length; i++)//loop for each char in the "Number" variable
{
if (Text[j] == Number[i]) //←System.IndexOutOfRangeException: 'Index was outside the bounds of the array.
{
ANumber = true;
}
}
if (!ANumber)
{
Answer = false;
}
}
return Answer;
}
它的作用是检查一个字符串,如果字符串全是数字就returntrue
如果字符串中有 non-number 个字符,则 return 为 false。
但是在循环中,有一个错误提示 indexOutOfRange,但我很确定它不是。那么我该如何修复这个变量呢?
或者如果您有更好的工作变量来检查字符串是否为数字,让我知道 :)
谢谢您的帮助。
另外,如果您对这个论坛的标题有什么建议,请告诉我,我会修改名称。
你用 i
打印错了 j
:
if (Text[j] == Number[i])
string text = "12345678909876543234a";
for(int j = 0; j < Text.Length; j++)
{
if(!char.IsNumber(Text[j]))
{
return false;
}
}
return true;
所以我有一个名为 isNumber 的 bool Variabel。
bool isNumber(string Text)
{
bool Answer = true;
string Number = "1234567890";
bool ANumber = false;
for(int j = 0; j <Text.Length; j++)//loop for each char in string Text
{
for (int i = 0; i < Number.Length; i++)//loop for each char in the "Number" variable
{
if (Text[j] == Number[i]) //←System.IndexOutOfRangeException: 'Index was outside the bounds of the array.
{
ANumber = true;
}
}
if (!ANumber)
{
Answer = false;
}
}
return Answer;
}
它的作用是检查一个字符串,如果字符串全是数字就returntrue 如果字符串中有 non-number 个字符,则 return 为 false。
但是在循环中,有一个错误提示 indexOutOfRange,但我很确定它不是。那么我该如何修复这个变量呢?
或者如果您有更好的工作变量来检查字符串是否为数字,让我知道 :) 谢谢您的帮助。 另外,如果您对这个论坛的标题有什么建议,请告诉我,我会修改名称。
你用 i
打印错了 j
:
if (Text[j] == Number[i])
string text = "12345678909876543234a";
for(int j = 0; j < Text.Length; j++)
{
if(!char.IsNumber(Text[j]))
{
return false;
}
}
return true;