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?
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 }
If you want to check if the input is in hexadecimal format, you shouldn't trim it at the beginning. Also, your loop could fail faster if you just return false on the first occurrence of a non-hex character (there's probably some method to check for containment so you could do: if (! hexDigits.
Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.
Something like this:
(I don't know C# so I'm not sure how to loop through the chars of a string.)
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; }
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With