簡體   English   中英

檢查字符串以查看是否所有字符都是十六進制值

[英]Check a string to see if all characters are hexadecimal values

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

像這樣的東西:

(我不知道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;

上面的邏輯代碼

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;
}
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");
}

您可以對字符串執行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);

我使用Int32.TryParse()來做到這一點。 這是MSDN頁面

這是上面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);
}

怎么樣:

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

這基本上說:檢查text字符串中的所有字符是否確實存在於有效的十六進制值字符串中。

對我來說哪個是最簡單的可讀解決方案。

(別忘了using System.Linq;添加using System.Linq;

編輯:
剛剛注意到Enumerable.All()僅在.NET 3.5之后才可用。

正則表達式在最好的時候效率不高。 最有效的方法是使用plain for循環來搜索字符串的字符,並在找到的第一個無效字符上中斷。

但是,它可以用LINQ非常簡潔地完成:

bool isHex = 
    myString.ToCharArray().Any(c => !"0123456789abcdefABCDEF".Contains(c));

我無法保證效率,因為LINQ是LINQ,但Any()應該有一個非常優化的編譯方案。

發布了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
    //Another workaround, although RegularExpressions is the best solution
     boolean OnlyHexInString(String text)
    {
      for(int i = 0; i < text.size(); i++)
        if( !Uri.IsHexDigit(text.charAt(i)) )
          return false;
      return true;
    }

在性能方面,最快的可能是簡單地枚舉字符並進行簡單的比較檢查。

bool OnlyHexInString(string text) {
  for (var i = 0; i < text.Length; i++) {
    var current = text[i];
    if (!(Char.IsDigit(current) || (current >= 'a' && current <= 'f'))) {
      return false;
    }
  }
  return true;
}

要真正了解哪種方法最快,您需要進行一些分析。

程序員時間而言 ,最好調用平台的字符串到整數解析函數(例如Java的Integer.parseInt(str,base) ),看看是否有異常。 如果你想自己寫,可能更有時間/空間效率......

我認為效率最高的是每個角色的查找表。 您將擁有2 ^ 8(或2 ^ 16 for Unicode)-entry數組的布爾值,如果它是有效的十六進制字符,則每個布爾值都為 ,否則為 代碼看起來像(在Java中,對不起;-):

boolean lut[256]={false,false,true,........}

boolean OnlyHexInString(String text)
{
  for(int i = 0; i < text.size(); i++)
    if(!lut[text.charAt(i)])
      return false;
  return true;
}

這可以使用正則表達式來完成,這是檢查字符串是否與特定模式匹配的有效方法。

十六進制數字的可能正則表達式是[A-Ha-h0-9] ,一些實現甚至具有十六進制數字的特定代碼,例如[[:xdigit:]]

您可以使用以下方式擴展字符串和字符:

    public static bool IsHex(this string value)
    {   return value.All(c => c.IsHex()); }

    public static bool IsHex(this char c)
    {
        c = Char.ToLower(c);
        if (Char.IsDigit(c) || (c >= 'a' && c <= 'f'))
            return true;
        else
            return false;
    }

沒有正則表達式的簡單解決方案是:

VB.NET:

Public Function IsHexString(value As String) As Boolean
    Dim hx As String = "0123456789ABCDEF"
    For Each c As Char In value.ToUpper
        If Not hx.Contains(c) Then Return False
    Next
    Return True
End Function

或者在C#中

public bool IsHexString(string value)
{
    string hx = "0123456789ABCDEF";
    foreach (char c in value.ToUpper()) {
        if (!hx.Contains(c))
        return false;
    }
    return true;
}

我用這個方法:

public static bool IsHex(this char c)
{
  return   (c >= '0' && c <= '9') ||
           (c >= 'a' && c <= 'f') ||
           (c >= 'A' && c <= 'F');
}

而這作為C#擴展方法......

public static class StringExtensions
{
    public static bool IsHexString(this string str)
    {
        foreach (var c in str)
        {
            var isHex = ((c >= '0' && c <= '9') ||
                          (c >= 'a' && c <= 'f') ||
                          (c >= 'A' && c <= 'F'));

            if (!isHex)
            {
                return false;
            }
        }

        return true;
    }

    //bonus, verify whether a string can be parsed as byte[]
    public static bool IsParseableToByteArray(this string str)
    {
        return IsHexString(str) && str.Length % 2 == 0;
    }
}

像這樣使用它......

if("08c9b54d1099e73d121c4200168f252e6e75d215969d253e074a9457d0401cc6".IsHexString())
{
    //returns true...
}

我提出這個解決方案來解決這個問題。 執行前檢查Request字符串是否為null。

for (int i = 0; i < Request.Length; i += 2)
  if (!byte.TryParse(string.Join("", Request.Skip(i).Take(2)), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)) return false;
public static bool HexInCardUID(string test)
        {
            if (test.Trim().Length != 14)
                return false;
            for (int i = 0; i < test.Length; i++)
                if (!Uri.IsHexDigit(Convert.ToChar(test.Substring(i, 1))))
                    return false;
            return true;
        }**strong text**

現在只

if (IsHex(text)) {
    return true;
} else {
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM