在C#2.0中检查字符串中每个字符的最有效方法是什么?如果它们都是有效的十六进制字符则返回true,否则返回false?
void Test()
{
OnlyHexInString("123ABC"); // Returns true
OnlyHexInString("123def"); // Returns true
OnlyHexInString("123g"); // Returns false
}
bool OnlyHexInString(string text)
{
// Most efficient algorithm to check each digit in C# 2.0 goes here
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*ten 72
像这样的东西:
(我不知道C#所以我不知道如何循环字符串的字符.)
loop through the chars {
bool is_hex_char = (current_char >= '0' && current_char <= '9') ||
(current_char >= 'a' && current_char <= 'f') ||
(current_char >= 'A' && current_char <= 'F');
if (!is_hex_char) {
return false;
}
}
return true;
Run Code Online (Sandbox Code Playgroud)
上面的逻辑代码
private bool IsHex(IEnumerable<char> chars)
{
bool isHex;
foreach(var c in chars)
{
isHex = ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'));
if(!isHex)
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 64
public bool OnlyHexInString(string test)
{
// For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z"
return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z");
}
Run Code Online (Sandbox Code Playgroud)
Eoi*_*ell 27
您可以对字符串执行TryParse以测试其整数中的字符串是否为十六进制数.
如果它是一个特别长的字符串,你可以把它放在块中并循环遍历它.
// string hex = "bacg123"; Doesn't parse
// string hex = "bac123"; Parses
string hex = "bacg123";
long output;
long.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out output);
Run Code Online (Sandbox Code Playgroud)
这是上面yjerem解决方案的LINQ版本:
private static bool IsValidHexString(IEnumerable<char> hexString)
{
return hexString.Select(currentCharacter =>
(currentCharacter >= '0' && currentCharacter <= '9') ||
(currentCharacter >= 'a' && currentCharacter <= 'f') ||
(currentCharacter >= 'A' && currentCharacter <= 'F')).All(isHexCharacter => isHexCharacter);
}
Run Code Online (Sandbox Code Playgroud)
怎么样:
bool isHex = text.All("0123456789abcdefABCDEF".Contains);
这基本上说:检查text
字符串中的所有字符是否确实存在于有效的十六进制值字符串中.
对我来说哪个是最简单的可读解决方案.
(别忘了添加using System.Linq;
)
编辑:
刚刚注意到Enumerable.All()
只有.NET 3.5才可用.
发布Jeremy 答案的 VB.NET 版本,因为我是在寻找这样的版本时来到这里的。将其转换为 C# 应该很容易。
''' <summary>
''' Checks if a string contains ONLY hexadecimal digits.
''' </summary>
''' <param name="str">String to check.</param>
''' <returns>
''' True if string is a hexadecimal number, False if otherwise.
''' </returns>
Public Function IsHex(ByVal str As String) As Boolean
If String.IsNullOrWhiteSpace(str) Then _
Return False
Dim i As Int32, c As Char
If str.IndexOf("0x") = 0 Then _
str = str.Substring(2)
While (i < str.Length)
c = str.Chars(i)
If Not (((c >= "0"c) AndAlso (c <= "9"c)) OrElse
((c >= "a"c) AndAlso (c <= "f"c)) OrElse
((c >= "A"c) AndAlso (c <= "F"c))) _
Then
Return False
Else
i += 1
End If
End While
Return True
End Function
Run Code Online (Sandbox Code Playgroud)