我想在将它附加到StringBuilder之前对String进行检查,以确保字符串中只有数字字符.有什么简单的方法可以做到这一点?
小智 8
在VB.Net中编码以检查字符串是否仅包含数值.
If IsNumeric("your_text") Then
MessageBox.Show("yes")
Else
MessageBox.Show("no")
End If
Run Code Online (Sandbox Code Playgroud)
使用Integer.TryParse()如果字符串中只有数字,它将返回true.Int32最大值是2,147,483,647,所以如果你的价值低于那么你的罚款. http://msdn.microsoft.com/en-us/library/f02979c7.aspx
您还可以使用Double.TryParse(),其最大值为1.7976931348623157E + 308,但它将允许小数点.
如果您希望获得的值不是整数,则可以始终一次查看字符串
string test = "1112003212g1232";
int result;
bool append=true;
for (int i = 0; i < test.Length-1; i++)
{
if(!Int32.TryParse(test.Substring(i,i+1),out result))
{
//Not an integer
append = false;
}
}
Run Code Online (Sandbox Code Playgroud)
如果append保持为true,则字符串为整数.可能是一个更光滑的方式,但这应该工作.