我在检查字符串的内容时遇到问题 [英] I am having an issue in checking the contents of a string
问题描述
大家好,
我正在尝试将字符串转换为int但是遇到了我正在做的事情。我正在使用C#,序列号作为字符串读入。然后我用字符串属性.Length检查它的长度,以确保它是8个字符,短或太长的错误。这是工作我现在要检查它是数字(在0 - 9之间)我正在考虑做一个Convert.ToInt(32)来检查它是否是一个数字,如果它包含0-9以下的字符错误,我想要知道这样做的正确方法好像我用一个试试看起来有点重手吗?是否有IsNumeric类型命令? (或者我再次被剧本弄错了!)
格伦
我在思考/谷歌搜索中找到了Davey69的简单数字文本框
简单数字文本框 [ ^ ]但它似乎不太符合我的目的。
Hi All,
I am trying to convert a string to an int but have come across a twist with the way I am doing it. I am using C# and a serial number is read in as a string. I am then checking it''s length with the string property .Length to ensure it is 8 characters to short or too long errors. That is working I now what to check it is numeric (between 0 - 9) I was thinking of doing a Convert.ToInt(32) to check if its a number if it contains characters of than 0-9 it errors, I would like to know the correct way of doing this as if I use a try catch it seems a little heavy handed? Is there a IsNumeric type command ? (or a I being poisned by script again!)
Glenn
I have in thinking/googling found Davey69''s Simple Numeric Text Box at
Simple Numeric TextBox[^] but it does seem a not quite right for my purpose.
推荐答案
您可以使用正则表达式来确保它们都是数字,或者您可以使用int.TryParse:
You could use a regex to ensure they are all digits, or you could just use int.TryParse:
string serial = "98765432";
int serialNo;
if (int.TryParse(serial, out serialNo))
{
Console.WriteLine(serialNo);
}
您可能想要添加的唯一内容是对输入进行修剪,因为TryParse在以空格开头和/或结尾的数字上不会失败。
The only thing you might want to add is a Trim to the input, as TryParse will not fail on numbers starting and / or ending with whitespace.
我使用的例程是:
The routine I use is:
public System.Boolean IsNumeric(System.Object Expression)
{
if(Expression == null || Expression is DateTime)
return false;
if(Expression is Int16 || Expression is Int32 ||
Expression is Int64 || Expression is Decimal ||
Expression is Single || Expression is Double ||
Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
return false;
}
因此,要测试字符串中的字符,您可以编写:
So to test a character in a string, for example, you can then write:
if (IsNumeric(myString.Substring(4, 5))
{
// success
}
或者测试一个完整的字符串:
Or to test a full string:
if (IsNumeric(myString)
{
// success
}
只是为了给你一个提示,你怎么用正则表达式解决它...
Just to give you a hint, how you could solve it using Regex...
string serial = "12345678";
string pattern = @"^\d{8}
这篇关于我在检查字符串的内容时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!