Compare two alphanumeric string in python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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++

    #include

    using namespace std;

    bool CompareAlphanumeric(string& str1, string& str2)

    {

        int i, j;

        i = 0;

        j = 0;

        int len1 = str1.size();

        int len2 = str2.size();

        while (i <= len1 && j <= len2) {

            while (i < len1

                   && (!((str1[i] >= 'a' && str1[i] <= 'z')

                         || (str1[i] >= 'A' && str1[i] <= 'Z')

                         || (str1[i] >= '0' && str1[i] <= '9')))) {

                i++;

            }

            while (j < len2

                   && (!((str2[j] >= 'a' && str2[j] <= 'z')

                         || (str2[j] >= 'A' && str2[j] <= 'Z')

                         || (str2[j] >= '0' && str2[j] <= '9')))) {

                j++;

            }

            if (i == len1 && j == len2)

                return true;

            else if (str1[i] != str2[j])

                return false;

            else {

                i++;

                j++;

            }

        }

        return false;

    }

    void CompareAlphanumericUtil(string str1, string str2)

    {

        bool res;

        res = CompareAlphanumeric(str1, str2);

        if (res == true)

            cout << "Equal" << endl;

        else

            cout << "Unequal" << endl;

    }

    int main()

    {

        string str1, str2;

        str1 = "Ram, Shyam";

        str2 = " Ram - Shyam.";

        CompareAlphanumericUtil(str1, str2);

        str1 = "abc123";

        str2 = "123abc";

        CompareAlphanumericUtil(str1, str2);

        return 0;

    }

    Java

    import java.util.*;

    class GFG

    {

    static boolean CompareAlphanumeric(char[] str1,

                                       char[] str2)

    {

        int i, j;

        i = 0;

        j = 0;

        int len1 = str1.length;

        int len2 = str2.length;

        while (i <= len1 && j <= len2)

        {

            while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') ||

                                  (str1[i] >= 'A' && str1[i] <= 'Z') ||

                                  (str1[i] >= '0' && str1[i] <= '9'))))

            {

                i++;

            }

            while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') ||

                                  (str2[j] >= 'A' && str2[j] <= 'Z') ||

                                  (str2[j] >= '0' && str2[j] <= '9'))))

            {

                j++;

            }

            if (i == len1 && j == len2)

            {

                return true;

            }

            else if (str1[i] != str2[j])

            {

                return false;

            }

            else

            {

                i++;

                j++;

            }

        }

        return false;

    }

    static void CompareAlphanumericUtil(String str1,

                                        String str2)

    {

        boolean res;

        res = CompareAlphanumeric(str1.toCharArray(),

                                  str2.toCharArray());

        if (res == true)

        {

            System.out.println("Equal");

        }

        else

        {

            System.out.println("Unequal");

        }

    }

    public static void main(String[] args)

    {

        String str1, str2;

        str1 = "Ram, Shyam";

        str2 = " Ram - Shyam.";

        CompareAlphanumericUtil(str1, str2);

        str1 = "abc123";

        str2 = "123abc";

        CompareAlphanumericUtil(str1, str2);

    }

    }

    Python3

    def CompareAlphanumeric(str1, str2):

        i = 0

        j = 0

        len1 = len(str1)

        len2 = len(str2)

        while (i <= len1 and j <= len2):

            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

            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 (i == len1 and j == len2):

                return True

            elif (str1[i] != str2[j]):

                return False

            else:

                i += 1

                j += 1

        return False

    def CompareAlphanumericUtil(str1, str2):

        res = CompareAlphanumeric(str1, str2)

        if (res == True):

            print("Equal")

        else:

            print("Unequal")

    if __name__ == '__main__':

        str1 = "Ram, Shyam"

        str2 = " Ram - Shyam."

        CompareAlphanumericUtil(str1, str2)

        str1 = "abc123"

        str2 = "123abc"

        CompareAlphanumericUtil(str1, str2)

    C#

    using System;

    class GFG

    {

        static bool CompareAlphanumeric(char []str1,

                                        char []str2)

        {

            int i, j;

            i = 0;

            j = 0;

            int len1 = str1.Length;

            int len2 = str2.Length;

            while (i <= len1 && j <= len2)

            {

                while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') ||

                                      (str1[i] >= 'A' && str1[i] <= 'Z') ||

                                      (str1[i] >= '0' && str1[i] <= '9'))))

                {

                    i++;

                }

                while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') ||

                                      (str2[j] >= 'A' && str2[j] <= 'Z') ||

                                      (str2[j] >= '0' && str2[j] <= '9'))))

                {

                    j++;

                }

                if (i == len1 && j == len2)

                {

                    return true;

                }

                else if (str1[i] != str2[j])

                {

                    return false;

                }

                else

                {

                    i++;

                    j++;

                }

            }

            return false;

        }

        static void CompareAlphanumericUtil(string str1,

                                            string str2)

        {

            bool res;

            res = CompareAlphanumeric(str1.ToCharArray(),

                                      str2.ToCharArray());

            if (res == true)

            {

                Console.WriteLine("Equal");

            }

            else

            {

                Console.WriteLine("Unequal");

            }

        }

        public static void Main()

        {

            string str1, str2;

            str1 = "Ram, Shyam";

            str2 = " Ram - Shyam.";

            CompareAlphanumericUtil(str1, str2);

            str1 = "abc123";

            str2 = "123abc";

            CompareAlphanumericUtil(str1, str2);

        }

    }

    Javascript

    Time Complexity: O(n*n)
    Auxiliary Space: O(1), as no extra space is required


    How do you compare two alphanumeric strings in Python?

    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. Recommended: Please try your approach on {IDE} first, before moving on to the solution.

    How do you compare alphanumeric?

    An alphanumeric comparison is a comparison of the single-byte character values of two operands..
    For the EBCDIC character set, the EBCDIC collating sequence is used..
    For the ASCII character set, the ASCII collating sequence is used..

    How do you compare two letters in a string?

    strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);

    How do you check if two strings are alphabetical order in Python?

    Comparing Strings with <, >, <=, and >= To compare strings alphabetically, you can use the operators <, >, <=, >=.