检查字符串以查看是否所有字符都是十六进制值

Guy*_*Guy 52 c#

在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)

  • 对于一个有锤子的男人来说,每个问题看起来都像一个钉子 (56认同)
  • 我觉得奇怪的是,有很多人为了这个而跳上正则表达式...... (13认同)

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)

  • 对于问题所暗示的速度,您需要编译正则表达式而不是连续地对其进行求值. (8认同)
  • 编译或不编译,这是问题... http://tinyurl.com/6ltmxv (4认同)
  • 根本没有使用正则表达式来解决这个问题吗?有一天我将不得不衡量它,但我不敢相信它会比Jeremy Ruten的解决方案更快(http://stackoverflow.com/questions/223832/check-a-string-to-see-if-all -characters-是十六进制值#223854). (4认同)
  • 确实 - 快速测试(在Jon Skeet的Micro Benchmark代码的帮助下)显示,即使使用预编译的正则表达式,Jeremy Ruten概述的简单技术也要快5倍. (4认同)
  • 程序员效率v.程序效率.像往常一样,真正的答案是'它取决于'.链接@CMS的Thx. (3认同)

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)


its*_*att 10

我习惯Int32.TryParse()这样做. 这是MSDN页面.

  • @Roy"所有这些字符都是有效的十六进制字符之间有区别吗?" vs"这个字符串是否可解析为十六进制并且适合Int32?" 你提出了一个很好的观点,但假设OP正在转换Int32十六进制值是否安全? (3认同)

Rob*_*ein 7

这是上面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)

  • 小说,它很容易击败正则表达式版本.但是原始while循环仍然比LINQ快. (4认同)
  • return!hexString.Any(c =>!(c> ='0'&& c <='9')&&!(c> ='a'&& c <='f')&&!(c> ='A '&& c <='F')); (2认同)

Kap*_*apé 7

怎么样:

bool isHex = text.All("0123456789abcdefABCDEF".Contains);

这基本上说:检查text字符串中的所有字符是否确实存在于有效的十六进制值字符串中.

对我来说哪个是最简单的可读解决方案.

(别忘了添加using System.Linq;)

编辑:
刚刚注意到Enumerable.All()只有.NET 3.5才可用.


Kum*_*mba 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)