Check if a given string is a valid Hexadecimal Color Code or not - GeeksforGeeks

17 Nov, 2021
Given a string str, the task is to check whether the given string is an HTML Hex Color Code or not. Print Yes if it is, otherwise print No.
Examples: 
Input: str = “#1AFFa1”Output: Yes
Input: str = “#F00”Output: Yes
Input: str = “123456”Output: No
Approach:  An HTML Hex Color Code follows the below-mentioned set of rules: 
It starts with the ‘#’ symbol.Then it is followed by the letters from a-f, A-F and/or digits from 0-9.The length of the hexadecimal color code should be either 6 or 3, excluding ‘#’ symbol.For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.
It starts with the ‘#’ symbol.
Then it is followed by the letters from a-f, A-F and/or digits from 0-9.
The length of the hexadecimal color code should be either 6 or 3, excluding ‘#’ symbol.
For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.
Now, to solve the above problem follow the below steps:
Check the string str for the following conditions:If the first character is not #, return false.If the length is not 3 or 6. If not, return false.Now, check for all characters other than the first character that are 0-9, A-F or a-f.If all the conditions mentioned above are satisfied, then return true.Print answer according to the above observation.
Check the string str for the following conditions:If the first character is not #, return false.If the length is not 3 or 6. If not, return false.Now, check for all characters other than the first character that are 0-9, A-F or a-f.
If the first character is not #, return false.
If the length is not 3 or 6. If not, return false.
Now, check for all characters other than the first character that are 0-9, A-F or a-f.
If all the conditions mentioned above are satisfied, then return true.
Print answer according to the above observation.
Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// C++ program for the above approach #include <iostream>using namespace std; // Function to validate// the HTML hexadecimal color code.bool isValidHexaCode(string str){    if (str[0] != '#')        return false;     if (!(str.length() == 4 or str.length() == 7))        return false;     for (int i = 1; i < str.length(); i++)        if (!((str[i] >= '0' && str[i] <= 9)              || (str[i] >= 'a' && str[i] <= 'f')              || (str[i] >= 'A' || str[i] <= 'F')))            return false;     return true;} // Driver Codeint main(){    string str = "#1AFFa1";     if (isValidHexaCode(str)) {        cout << "Yes" << endl;    }    else {        cout << "No" << endl;    }    return 0;}
// Java program for the above approachimport java.util.*;class GFG{     // Function to validate    // the HTML hexadecimal color code.    static boolean isValidHexaCode(String str)    {        if (str.charAt(0) != '#')            return false;         if (!(str.length() == 4 || str.length() == 7))            return false;         for (int i = 1; i < str.length(); i++)            if (!((str.charAt(i) >= '0' && str.charAt(i) <= 9)                || (str.charAt(i) >= 'a' && str.charAt(i) <= 'f')                || (str.charAt(i) >= 'A' || str.charAt(i) <= 'F')))                return false;         return true;    }         // Driver code    public static void main(String args[])    {        String str = "#1AFFa1";         if (isValidHexaCode(str)) {            System.out.println("Yes");        }        else {            System.out.println("No");        }    }} // This code is contributed by Samim Hossain Mondal.
# python program for the above approach # Function to validate# the HTML hexadecimal color code.def isValidHexaCode(str):     if (str[0] != '#'):        return False     if (not(len(str) == 4 or len(str) == 7)):        return False     for i in range(1, len(str)):        if (not((str[i] >= '0' and str[i] <= '9') or (str[i] >= 'a' and str[i] <= 'f') or (str[i] >= 'A' or str[i] <= 'F'))):            return False     return True  # Driver Codeif __name__ == "__main__":     str = "#1AFFa1"     if (isValidHexaCode(str)):        print("Yes")     else:        print("No")     # This code is contributed by rakeshsahni
// C# program for the above approachusing System;class GFG{     // Function to validate    // the HTML hexadecimal color code.    static bool isValidHexaCode(string str)    {        if (str[0] != '#')            return false;         if (!(str.Length == 4 || str.Length == 7))            return false;         for (int i = 1; i < str.Length; i++)            if (!((str[i] >= '0' && str[i] <= 9)                || (str[i] >= 'a' && str[i] <= 'f')                || (str[i] >= 'A' || str[i] <= 'F')))                return false;         return true;    }         // Driver code    public static void Main()    {        string str = "#1AFFa1";         if (isValidHexaCode(str)) {            Console.Write("Yes");        }        else {            Console.Write("No");        }    }}// This code is contributed by Samim Hossain Mondal.
<script>       // JavaScript Program to implement       // the above approach        // Function to validate       // the HTML hexadecimal color code.       function isValidHexaCode(str) {           if (str[0] != '#')               return false;            if (!(str.length == 4 || str.length == 7))               return false;            for (let i = 1; i < str.length; i++)               if (!((str[i].charCodeAt(0) <= '0'.charCodeAt(0) && str[i].charCodeAt(0) <= 9)                   || (str[i].charCodeAt(0) >= 'a'.charCodeAt(0) && str[i].charCodeAt(0) <= 'f'.charCodeAt(0))                   || (str[i].charCodeAt(0) >= 'A'.charCodeAt(0) || str[i].charCodeAt(0) <= 'F'.charCodeAt(0))))                   return false;            return true;       }        // Driver Code       let str = "#1AFFa1";        if (isValidHexaCode(str)) {           document.write("Yes" + '<br>');       }       else {           document.write("No" + '<br>');       }    // This code is contributed by Potta Lokesh   </script>
Yes
Time Complexity: O(N)Auxiliary Space: O(1)
rakeshsahni
gfgking
lokeshpotta20
samim2000
simmytarika5
Mathematical
Pattern Searching
Strings
Strings
Mathematical
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Naive algorithm for Pattern Searching
Boyer Moore Algorithm for Pattern Searching