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

时间:2023-01-19 20:21:58

What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise?

在c# 2.0中,最有效的方法是检查字符串中的每个字符并返回true,如果它们都是有效的十六进制字符,反之则是假的?

Example

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
}

19 个解决方案

#1


55  

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

#2


67  

Something like this:

是这样的:

(I don't know C# so I'm not sure how to loop through the chars of a string.)

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

Code for Logic Above

上面的代码逻辑

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

#3


24  

You can do a TryParse on the string to test if the string in its entirity is a hexadecimal number.

您可以在字符串上进行TryParse,以测试其entirity中的字符串是否为十六进制数。

If it's a particularly long string, you could take it in chunks and loop through it.

如果它是一个特别长的字符串,你可以把它分成块,然后循环。

// 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);

#4


7  

Here is a LINQ version of yjerem's solution above:

这里有一个LINQ版的yjerem解决方案:

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

#5


7  

I use Int32.TryParse() to do this. Here's the MSDN page on it.

我使用Int32.TryParse()来做这个。这是MSDN页面。

#6


5  

What about just:

关于:

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

bool isHex = text.All(“0123456789 abcdefabcdef”.Contains);

This basically says: check if all chars in the text string do exist in the valid hex values string.

这主要是说:检查文本字符串中的所有字符是否存在于有效的十六进制值字符串中。

Which is the simplest still readable solution to me.

对于我来说,这是最简单的可读的解决方案。

(don't forget to add using System.Linq;)

(别忘了使用System.Linq;)

EDIT:
Just noticed that Enumerable.All() is only available since .NET 3.5.

编辑:刚刚注意到枚举。all()只在。net 3.5中可用。

#7


4  

Posting a VB.NET version of Jeremy's answer, because I came here while looking for such a version. Should be easy to convert it to C#.

发布一个VB。网络版的杰里米的回答,因为我是在寻找这样一个版本的时候来到这里的。应该很容易将其转换为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

#8


4  

A regular expression is not very efficient at the best of times. The most efficient will be using a plain for loop to search through the characters of the string, and break on the first invalid one found.

一个正则表达式在最好的时候不是很有效。最有效的方法是使用一个简单的for循环来搜索字符串的字符,并在第一个找到的无效的字符串中进行破解。

However, it can be done very succinctly with LINQ:

但是,它可以用LINQ非常简洁地完成:

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

I cannot vouch for the efficiency, since LINQ is LINQ, but Any() should have a pretty well-optimised compilation scheme.

我不能保证效率,因为LINQ是LINQ,但是任何()都应该有一个非常优化的编译方案。

#9


3  

In terms of performance the fastest is likely to simply enumerate the characters and do a simple comparison check.

在性能方面,最快的可能是简单地枚举字符并做一个简单的比较检查。

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

To truly know which method is fastest though you'll need to do some profiling.

要真正知道哪种方法是最快的,您需要做一些分析。

#10


3  

    //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;
    }

#11


1  

In terms of programmer time, it's probably best to call your platform's string-to-integer parsing function (such as Java's Integer.parseInt(str, base)), and see if you get an exception. If you want to write it yourself, and potentially be more time/space-efficient...

就程序员时间而言,最好调用平台的字符串到整数解析函数(比如Java的整数)。parseInt(str, base)),看看是否有例外。如果你想自己写,而且可能有更多的时间/空间效率…

Most efficient I suppose would be a lookup table on each character. You would have a 2^8 (or 2^16 for Unicode)-entry array of booleans, each of which would be true if it is a valid hex character, or false if not. The code would look something like (in Java, sorry ;-):

最有效的方法是查找每个字符的查找表。您将有一个2 8(或2 16)的布尔值条目数组,如果它是一个有效的十六进制字符,则每一个都是正确的,如果不是,则为false。代码看起来像(在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;
}

#12


0  

This could be done with regular expressions, which are an efficient way of checking if a string matches a particular pattern.

这可以用正则表达式来完成,这是检查字符串是否匹配特定模式的一种有效方法。

A possible regular expression for a hex digit would be [A-Ha-h0-9], some implementations even have a specific code for hex digits, e.g. [[:xdigit:]].

对于十六进制数字的一个可能的正则表达式是[A- ha -h0-9],有些实现甚至有一个特定的十六进制数字代码,例如[[:xdigit:]]。

#13


0  

You can Extend string and char using someting like this:

可以使用如下方式扩展字符串和char:

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

#14


0  

An easy solution without regular expressions is:

没有正则表达式的简单解决方案是:

VB.NET:

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

Or in C#

或在c#中

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

#15


0  

I use this method:

我用这个方法:

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

#16


0  

And this as C# extension method...

这是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;
    }
}

Use it like so...

使用它就像……

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

#17


0  

I made this solution to come around this issue. Check that the Request string is not null before executing.

我解决了这个问题。在执行之前检查请求字符串是否为空。

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;

#18


0  

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**

#19


-4  

Now, only

现在,只

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

#1


55  

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

#2


67  

Something like this:

是这样的:

(I don't know C# so I'm not sure how to loop through the chars of a string.)

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

Code for Logic Above

上面的代码逻辑

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

#3


24  

You can do a TryParse on the string to test if the string in its entirity is a hexadecimal number.

您可以在字符串上进行TryParse,以测试其entirity中的字符串是否为十六进制数。

If it's a particularly long string, you could take it in chunks and loop through it.

如果它是一个特别长的字符串,你可以把它分成块,然后循环。

// 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);

#4


7  

Here is a LINQ version of yjerem's solution above:

这里有一个LINQ版的yjerem解决方案:

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

#5


7  

I use Int32.TryParse() to do this. Here's the MSDN page on it.

我使用Int32.TryParse()来做这个。这是MSDN页面。

#6


5  

What about just:

关于:

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

bool isHex = text.All(“0123456789 abcdefabcdef”.Contains);

This basically says: check if all chars in the text string do exist in the valid hex values string.

这主要是说:检查文本字符串中的所有字符是否存在于有效的十六进制值字符串中。

Which is the simplest still readable solution to me.

对于我来说,这是最简单的可读的解决方案。

(don't forget to add using System.Linq;)

(别忘了使用System.Linq;)

EDIT:
Just noticed that Enumerable.All() is only available since .NET 3.5.

编辑:刚刚注意到枚举。all()只在。net 3.5中可用。

#7


4  

Posting a VB.NET version of Jeremy's answer, because I came here while looking for such a version. Should be easy to convert it to C#.

发布一个VB。网络版的杰里米的回答,因为我是在寻找这样一个版本的时候来到这里的。应该很容易将其转换为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

#8


4  

A regular expression is not very efficient at the best of times. The most efficient will be using a plain for loop to search through the characters of the string, and break on the first invalid one found.

一个正则表达式在最好的时候不是很有效。最有效的方法是使用一个简单的for循环来搜索字符串的字符,并在第一个找到的无效的字符串中进行破解。

However, it can be done very succinctly with LINQ:

但是,它可以用LINQ非常简洁地完成:

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

I cannot vouch for the efficiency, since LINQ is LINQ, but Any() should have a pretty well-optimised compilation scheme.

我不能保证效率,因为LINQ是LINQ,但是任何()都应该有一个非常优化的编译方案。

#9


3  

In terms of performance the fastest is likely to simply enumerate the characters and do a simple comparison check.

在性能方面,最快的可能是简单地枚举字符并做一个简单的比较检查。

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

To truly know which method is fastest though you'll need to do some profiling.

要真正知道哪种方法是最快的,您需要做一些分析。

#10


3  

    //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;
    }

#11


1  

In terms of programmer time, it's probably best to call your platform's string-to-integer parsing function (such as Java's Integer.parseInt(str, base)), and see if you get an exception. If you want to write it yourself, and potentially be more time/space-efficient...

就程序员时间而言,最好调用平台的字符串到整数解析函数(比如Java的整数)。parseInt(str, base)),看看是否有例外。如果你想自己写,而且可能有更多的时间/空间效率…

Most efficient I suppose would be a lookup table on each character. You would have a 2^8 (or 2^16 for Unicode)-entry array of booleans, each of which would be true if it is a valid hex character, or false if not. The code would look something like (in Java, sorry ;-):

最有效的方法是查找每个字符的查找表。您将有一个2 8(或2 16)的布尔值条目数组,如果它是一个有效的十六进制字符,则每一个都是正确的,如果不是,则为false。代码看起来像(在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;
}

#12


0  

This could be done with regular expressions, which are an efficient way of checking if a string matches a particular pattern.

这可以用正则表达式来完成,这是检查字符串是否匹配特定模式的一种有效方法。

A possible regular expression for a hex digit would be [A-Ha-h0-9], some implementations even have a specific code for hex digits, e.g. [[:xdigit:]].

对于十六进制数字的一个可能的正则表达式是[A- ha -h0-9],有些实现甚至有一个特定的十六进制数字代码,例如[[:xdigit:]]。

#13


0  

You can Extend string and char using someting like this:

可以使用如下方式扩展字符串和char:

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

#14


0  

An easy solution without regular expressions is:

没有正则表达式的简单解决方案是:

VB.NET:

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

Or in C#

或在c#中

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

#15


0  

I use this method:

我用这个方法:

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

#16


0  

And this as C# extension method...

这是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;
    }
}

Use it like so...

使用它就像……

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

#17


0  

I made this solution to come around this issue. Check that the Request string is not null before executing.

我解决了这个问题。在执行之前检查请求字符串是否为空。

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;

#18


0  

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**

#19


-4  

Now, only

现在,只

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