Compare two strings considering only alphanumeric characters - GeeksforGeeks

03 Jun, 2021
Given two strings that can contain lower and uppercase alphabets, numbers and special characters like dots, blank spaces, commas, etc. Compare both strings considering only alphanumeric characters([a-b], [A-B] and [0-9]) if they are equal or not. For example, strings “Ram, Shyam” and “Ram-Shyam” both are the same and also “/.’;[]” and “@# >” are same.
Examples: 
Input: str1 = "Ram, Shyam", str2 = " Ram - Shyam."
Output: Equal
Explanation: 
if we ignore all characters 
except alphanumeric characters 
then strings will be, 
str1 = "RamShyam" and str2 = "RamShyam". 
Therefore both strings are equal.

Input : str1 = "aaa123", str2 = "@aaa-12-3"
Output : Equal

Input : str1 = "abc123", str2 = "123abc"
Output : Unequal
Explanation: 
In this, str1 = "abc123" and str2 = "123abc". 
Therefore both strings are not equal.
Since we have to compare only alphanumeric characters therefore whenever any other character is found simply ignore it by increasing iterator pointer. For doing it simply take two integer variables i and j and initialize them by 0. Now run a loop to compare each and every character of both strings. Compare one by one if the character is alphanumeric otherwise increase the value of i or j by one.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std; // Function to check alphanumeric equality of both stringsbool CompareAlphanumeric(string& str1, string& str2){    // variable declaration    int i, j;    i = 0;    j = 0;     // Length of first string    int len1 = str1.size();     // Length of second string    int len2 = str2.size();     // To check each and every characters of both string    while (i <= len1 && j <= len2) {         // If the current character of the first string is not an        // alphanumeric character, increase the pointer i        while (i < len1               && (!((str1[i] >= 'a' && str1[i] <= 'z')                     || (str1[i] >= 'A' && str1[i] <= 'Z')                     || (str1[i] >= '0' && str1[i] <= '9')))) {            i++;        }         // If the current character of the second string is not an        // alphanumeric character, increase the pointer j        while (j < len2               && (!((str2[j] >= 'a' && str2[j] <= 'z')                     || (str2[j] >= 'A' && str2[j] <= 'Z')                     || (str2[j] >= '0' && str2[j] <= '9')))) {            j++;        }         // if all alphanumeric characters of both strings are same        // then return true        if (i == len1 && j == len2)            return true;         // if any alphanumeric characters of both strings are not same        // then return false        else if (str1[i] != str2[j])            return false;         // If current character matched,        // increase both pointers to check the next character        else {            i++;            j++;        }    }     // If not same, then return false    return false;} // Function to print Equal or Unequal if strings are same or notvoid CompareAlphanumericUtil(string str1, string str2){    bool res;     // check alphanumeric equality of both strings    res = CompareAlphanumeric(str1, str2);     // if both are alphanumeric equal, print Equal    if (res == true)        cout << "Equal" << endl;     // otherwise print Unequal    else        cout << "Unequal" << endl;} // Driver codeint main(){     string str1, str2;     str1 = "Ram, Shyam";    str2 = " Ram - Shyam.";    CompareAlphanumericUtil(str1, str2);     str1 = "abc123";    str2 = "123abc";    CompareAlphanumericUtil(str1, str2);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to check alphanumeric// equality of both stringsstatic boolean CompareAlphanumeric(char[] str1,                                   char[] str2){    // variable declaration    int i, j;    i = 0;    j = 0;     // Length of first string    int len1 = str1.length;     // Length of second string    int len2 = str2.length;     // To check each and every characters    // of both string    while (i <= len1 && j <= len2)    {         // If the current character of the first string is not an        // alphanumeric character, increase the pointer i        while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') ||                              (str1[i] >= 'A' && str1[i] <= 'Z') ||                              (str1[i] >= '0' && str1[i] <= '9'))))        {            i++;        }         // If the current character of the second string is not an        // alphanumeric character, increase the pointer j        while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') ||                              (str2[j] >= 'A' && str2[j] <= 'Z') ||                              (str2[j] >= '0' && str2[j] <= '9'))))        {            j++;        }         // if all alphanumeric characters of        // both strings are same then return true        if (i == len1 && j == len2)        {            return true;        }                 // if any alphanumeric characters of        // both strings are not same then return false        else if (str1[i] != str2[j])        {            return false;        }                 // If current character matched,        // increase both pointers to        // check the next character        else        {            i++;            j++;        }    }     // If not same, then return false    return false;} // Function to print Equal or Unequal// if strings are same or notstatic void CompareAlphanumericUtil(String str1,                                    String str2){    boolean res;     // check alphanumeric equality of both strings    res = CompareAlphanumeric(str1.toCharArray(),                              str2.toCharArray());     // if both are alphanumeric equal,    // print Equal    if (res == true)    {        System.out.println("Equal");    }         // otherwise print Unequal    else    {        System.out.println("Unequal");    }} // Driver codepublic static void main(String[] args){    String str1, str2;     str1 = "Ram, Shyam";    str2 = " Ram - Shyam.";    CompareAlphanumericUtil(str1, str2);     str1 = "abc123";    str2 = "123abc";    CompareAlphanumericUtil(str1, str2);}} // This code is contributed by Rajput-Ji
# Function to check alphanumeric equality# of both stringsdef CompareAlphanumeric(str1, str2):         # variable declaration    i = 0    j = 0     # Length of first string    len1 = len(str1)     # Length of second string    len2 = len(str2)     # To check each and every character of both string    while (i <= len1 and j <= len2):                 # If the current character of the first string        # is not an alphanumeric character,        # increase the pointer i        while (i < len1 and              (((str1[i] >= 'a' and str1[i] <= 'z') or                (str1[i] >= 'A' and str1[i] <= 'Z') or                (str1[i] >= '0' and str1[i] <= '9')) == False)):            i += 1         # If the current character of the second string        # is not an alphanumeric character,        # increase the pointer j        while (j < len2 and              (((str2[j] >= 'a' and str2[j] <= 'z') or                (str2[j] >= 'A' and str2[j] <= 'Z') or                (str2[j] >= '0' and str2[j] <= '9')) == False)):            j += 1         # if all alphanumeric characters of        # both strings are same, then return true        if (i == len1 and j == len2):            return True         # if any alphanumeric characters of        # both strings are not same, then return false        elif (str1[i] != str2[j]):            return False         # If current character matched,        # increase both pointers        # to check the next character        else:            i += 1            j += 1     # If not same, then return false    return False # Function to print Equal or Unequal# if strings are same or notdef CompareAlphanumericUtil(str1, str2):         # check alphanumeric equality of both strings    res = CompareAlphanumeric(str1, str2)     # if both are alphanumeric equal, print Equal    if (res == True):        print("Equal")             # otherwise print Unequal    else:        print("Unequal") # Driver codeif __name__ == '__main__':    str1 = "Ram, Shyam"    str2 = " Ram - Shyam."    CompareAlphanumericUtil(str1, str2)     str1 = "abc123"    str2 = "123abc"    CompareAlphanumericUtil(str1, str2) # This code is contributed by Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{         // Function to check alphanumeric    // equality of both strings    static bool CompareAlphanumeric(char []str1,                                    char []str2)    {        // variable declaration        int i, j;        i = 0;        j = 0;             // Length of first string        int len1 = str1.Length;             // Length of second string        int len2 = str2.Length;             // To check each and every characters        // of both string        while (i <= len1 && j <= len2)        {                 // If the current character of the first            // string is not an alphanumeric character,            // increase the pointer i            while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') ||                                  (str1[i] >= 'A' && str1[i] <= 'Z') ||                                  (str1[i] >= '0' && str1[i] <= '9'))))            {                i++;            }                 // If the current character of the second            // string is not an alphanumeric character,            // increase the pointer j            while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') ||                                  (str2[j] >= 'A' && str2[j] <= 'Z') ||                                  (str2[j] >= '0' && str2[j] <= '9'))))            {                j++;            }                 // if all alphanumeric characters of            // both strings are same then return true            if (i == len1 && j == len2)            {                return true;            }                         // if any alphanumeric characters of            // both strings are not same then return false            else if (str1[i] != str2[j])            {                return false;            }                         // If current character matched,            // increase both pointers to            // check the next character            else            {                i++;                j++;            }        }             // If not same, then return false        return false;    }         // Function to print Equal or Unequal    // if strings are same or not    static void CompareAlphanumericUtil(string str1,                                        string str2)    {        bool res;             // check alphanumeric equality of both strings        res = CompareAlphanumeric(str1.ToCharArray(),                                  str2.ToCharArray());             // if both are alphanumeric equal,        // print Equal        if (res == true)        {            Console.WriteLine("Equal");        }                 // otherwise print Unequal        else        {            Console.WriteLine("Unequal");        }    }         // Driver code    public static void Main()    {        string str1, str2;             str1 = "Ram, Shyam";        str2 = " Ram - Shyam.";        CompareAlphanumericUtil(str1, str2);             str1 = "abc123";        str2 = "123abc";        CompareAlphanumericUtil(str1, str2);    }} // This code is contributed by AnkitRai01
<script>     // JavaScript implementation of the approach         // Function to check alphanumeric    // equality of both strings    function CompareAlphanumeric(str1, str2)    {        // variable declaration        let i, j;        i = 0;        j = 0;              // Length of first string        let len1 = str1.length;              // Length of second string        let len2 = str2.length;              // To check each and every characters        // of both string        while (i <= len1 && j <= len2)        {                  // If the current character of the first            // string is not an alphanumeric character,            // increase the pointer i            while (i < len1 &&            (!((str1[i].charCodeAt() >= 'a'.charCodeAt() &&            str1[i].charCodeAt() <= 'z'.charCodeAt()) ||            (str1[i].charCodeAt() >= 'A'.charCodeAt() &&            str1[i].charCodeAt() <= 'Z'.charCodeAt()) ||            (str1[i].charCodeAt() >= '0'.charCodeAt() &&            str1[i].charCodeAt() <= '9'.charCodeAt()))))            {                i++;            }                  // If the current character of the second            // string is not an alphanumeric character,            // increase the pointer j            while (j < len2 &&            (!((str2[j].charCodeAt() >= 'a'.charCodeAt() &&            str2[j].charCodeAt() <= 'z'.charCodeAt()) ||            (str2[j].charCodeAt() >= 'A'.charCodeAt() &&            str2[j].charCodeAt() <= 'Z'.charCodeAt()) ||            (str2[j].charCodeAt() >= '0'.charCodeAt() &&            str2[j].charCodeAt() <= '9'.charCodeAt()))))            {                j++;            }                  // if all alphanumeric characters of            // both strings are same then return true            if (i == len1 && j == len2)            {                return true;            }                          // if any alphanumeric characters of            // both strings are not same then return false            else if (str1[i] != str2[j])            {                return false;            }                          // If current character matched,            // increase both pointers to            // check the next character            else            {                i++;                j++;            }        }              // If not same, then return false        return false;    }          // Function to print Equal or Unequal    // if strings are same or not    function CompareAlphanumericUtil(str1, str2)    {        let res;              // check alphanumeric equality of both strings        res = CompareAlphanumeric(str1.split(''),                                  str2.split(''));              // if both are alphanumeric equal,        // print Equal        if (res == true)        {            document.write("Equal" + "</br>");        }                  // otherwise print Unequal        else        {            document.write("Unequal");        }    }         let str1, str2;          str1 = "Ram, Shyam";    str2 = " Ram - Shyam.";    CompareAlphanumericUtil(str1, str2);     str1 = "abc123";    str2 = "123abc";    CompareAlphanumericUtil(str1, str2); </script>
Equal
Unequal
 
Rajput-Ji
ankthon
SURENDRA_GANGWAR
akshaysingh98088
suresh07
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
sprintf() in C
Print all subsequences of a string
Convert character array to string in C++
How to Append a Character to a String in C
Program to count occurrence of a given character in a string
Naive algorithm for Pattern Searching