C#判断是不是合法的16进制字符串⽅法⼀:⽤判断,代码如下:
public const string PATTERN = @"([^A-Fa-f0-9]|\s+?)+";
/// <summary>
/// 判断⼗六进制字符串hex是否正确
/// </summary>
/// <param name="hex">⼗六进制字符串</param>
/// <returns>true:不正确,false:正确</returns>
public bool IsIllegalHexadecimal(string hex)
{
return System.Text.RegularExpressions.Regex.IsMatch(hex, PATTERN);
}
线性遍历输⼊的字符串中是否包含⾮⼗六进制字符,代码如下:⽅法⼆:
public IList<char> HexSet = new List<char>()
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','a','b','c','d','e','f' };
/// <summary>
/// 判断⼗六进制字符串hex是否正确
/// </summary>
/// <param name="hex">⼗六进制字符串</param>
/// <returns>true:不正确,false:正确</returns>
public bool IsIllegalHexadecimal(string hex)
{
foreach (char item in hex)
{
if (!HexSet.Contains<char>(item))
return true;
}
return false;
}
hex字符串是什么通过调⽤上述⽅法就可以清楚的知道输⼊的⼗六进制字符是否正确,然后为程序的下⼀个⼯作提供条件。还有⼀种⽅法性能⽐较慢就放到⽂章最后⾯了
/// <summary>
/// 判断是否为合法的16进制字符串
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public bool IsHexadecimal(string hexString)
{
try
{
hexString = hexString.Replace(" ", "").Replace("\r", "").Replace("\n", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
catch
{
return false;
}
return true;
}
#endregion
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论