Javatpoint Logo
Javatpoint Logo

Python Program to Count the Number of Matching Characters in a Pair of String

In this tutorial, we will discuss how the users can write a Python program for counting the number of matching characters in the given pair of strings.

We will pass the pair of non-empty strings. The program will count the number of matching characters in that pair of strings. Here, we will consider that the strings we passed are having duplicates of characters in them.

Example:

Approach 1:

  • Step 1: we will initialize the counter variable with 0.
  • Step 2: we will iterate over the first string from the first character to the last character.
  • Step 3: If the character extracted from the string_1 is found in the string_2. And if the first occurrence index of that character in the string_1 is the same as that of the index of the current extracted character, then it will increase the value of the counter by 1.

We will then use string.find('character') in Python to find the same characters. This will return the first occurrence index of the character in the string if found; otherwise, it will return "-1".

Example:

  • Step 4: print the output value of the counter.

Example: Method 1

Output:

Please enter the characters for String 1:  ajg 78y
Please enter the characters for String 2:  gjy 23r
The no. matching characters in the pairs of strings:  2

Approach 2:

  • Step 1: In this method, we will use the set() function for removing the duplicate on the given strings.
  • Step 2: We will use the set(intersection) on both strings.
  • Step 3: We will use the len() function for calculating the length of the "matched_characters_1" string.

Example 2: Method 2

Output:

Please enter the characters for String 1:  awe ret #$65
Please enter the characters for String 2:  rty urw @!34 
The number matching characters in the pairs of strings: 4

Approach 3:

  • Step 1: We will import the Re module.
  • Step 2: We will use the re.search() function to check if any character of string_1 is present in string_2 and if it does, then 1 will be added into the counter variable.

Example 3: Method 3

Output:

Please enter the characters for String 1: learning
Please enter the characters for String 2: working
The number matching characters in the pairs of strings: 5

Conclusion

In this tutorial, we have discussed different methods of writing a Python program for counting the number of matching characters in the given pair of strings.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA