Compare two strings considering only alphanumeric characters
Last Updated :
23 Jun, 2022
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 <iostream>
using namespace std;
// Function to check alphanumeric equality of both strings
bool 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 not
void 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 code
int main()
{
string str1, str2;
str1 = "Ram, Shyam";
str2 = " Ram - Shyam.";
CompareAlphanumericUtil(str1, str2);
str1 = "abc123";
str2 = "123abc";
CompareAlphanumericUtil(str1, str2);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to check alphanumeric
// equality of both strings
static 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 not
static 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 code
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);
}
}
// This code is contributed by Rajput-Ji
Python3
# Function to check alphanumeric equality
# of both strings
def 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 not
def 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 code
if __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#
// C# implementation of the approach
using 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
JavaScript
<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>
Time Complexity: O(n*n)
Auxiliary Space: O(1), as no extra space is required
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem