Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

c# - Check a string to see if all characters are hexadecimal values

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?

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...