Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




rindex( ) FUNCTION


rindex( ) Function


The rindex( ) Function is used to find the starting position of the substring.


Note : The rindex( ) Function is exactly similar to the find( ) function an index( ), the only difference is, the find( ) Function returns -1 if the value is not found and rindex( ) raises an exception.

Example :


x = "Hello Beautiful World"
y = x.rindex("Beautiful")
print("The substring is located at the position ",y)


Output :



  The substring is located at the position 6

In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.


x = "Hello Beautiful World"

java_Collections

And we would be searching the substring 'Beautiful', from the String, 'Hello Beautiful World'.


So, we have used the 'rindex( )' Function to find the substring 'Beautiful'.


y = x.find("Beautiful")

And what 'rindex( )' Function does is, goes to the String 'Hello Beautiful World' and searches for the position of the substring 'Beautiful'.


java_Collections

And finds the substring 'Beautiful' in the 6th position. And the position (i.e. '6') is stored in variable 'y'.


java_Collections

And thus prints the position.


print("The substring is located at the position ",y)

Output :



  The substring is located at the position 6

Now, let us say you have the below String,


"The Beautiful world is Beautiful indeed"

And you have to search for the second occurrence of 'Beautiful'.


To solve this, you can add a second and a third parameter used by 'rindex( )' function that tells the range, and in between the range the substring can be checked.


Let us see with the below example.


Example :


x = "The Beautiful world is Beautiful indeed"
y = x.rindex("Beautiful", 20, 35)
print("The substring is located at the position ",y)    


Output :



  The substring is located at the position 23

So, if you see the above output, only the second occurrence of 'Beautiful' is searched for.


That is because of the below line,


y = x.rindex("Beautiful", 20, 35)

Where we have specified the the range as '20' and '35', in second and third parameter.


Which says that search for the substring 'Beautiful' in the positions between '20' to '35'.


And thus we got the position as '23' assigned to the variable 'y',


java_Collections