/  Technology   /  Python string is a substring of another one means? 

Python string is a substring of another one means?

How to check if a given Python string is a substring of another one? 

Let’s understand this scenario with an example. We have been given two strings x and y. Now we have to check whether the given string y is a sub-string of the other string x

If y is a substring of x, then we return the index of its first occurrence and if not, then it will return -1.

 

   

 

We start traversing the string x and maintain an iterator(pointer), k for string y, from the 0th index.

We compare the current character in x for every iteration and check it with the index element where the iterator is currently present in y.

If matched, we increment the iterator k on y by 1. And if there’s a mismatch we re-initialise the iterator back to 0.

We’ll have to keep an eye on the iterator position as when its value is equal to the length of string y, we break the execution there and return the value 

 

(iterator pointing index of string a – iterator pointing index of string b)

Now we’ll combine all these steps and write a program.

The advantage of this method is that it works efficiently which involves strings with duplicate characters.

Leave a comment