C# 检查字符串以查看是否所有字符都是十六进制值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/223832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check a string to see if all characters are hexadecimal values
提问by Guy
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 否则返回 false 的最有效方法是什么?
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
}
采纳答案by CMS
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");
}
回答by itsmatt
I use Int32.TryParse()
to do this. Here's the MSDN page on it.
我Int32.TryParse()
用来做这个。 这是它的 MSDN 页面。
回答by Matt J
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 的Integer.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 trueif it is a valid hex character, or falseif not. The code would look something like (in Java, sorry ;-):
我认为最有效的是每个字符的查找表。您将有一个 2^8(或 2^16 为 Unicode)的布尔值条目数组,如果它是有效的十六进制字符,则每个数组都为真,否则为假。代码看起来像(在 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;
}
回答by Eoin Campbell
You can do a TryParseon the string to test if the string in its entirity is a hexadecimal number.
您可以对字符串执行TryParse以测试其整体中的字符串是否为十六进制数。
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);
回答by Jeremy Ruten
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;
}
回答by marcj
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:]]。
回答by Robert Bernstein
Here is a LINQ version of yjerem's solution above:
这是上面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);
}
回答by Kumba
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#.
发布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
回答by JaredPar
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.
要真正知道哪种方法最快,尽管您需要进行一些分析。
回答by Prueba
Now, only
现在只
if (IsHex(text)) {
return true;
} else {
return false;
}