Groovy – indexOf()

  • Post author:
  • Post category:Groovy
  • Post comments:2 Comments
Index

Returns the index within this String of the first occurrence of the specified substring. This method has 4 different variants.

  • public int indexOf(int ch) βˆ’ Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.

Syntax

public int indexOf(int ch)

Parameters

ch – The character to search for in the string.

Return Value

Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.

  • public int indexOf(int ch, int fromIndex) βˆ’ Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or 1 if the character does not occur.

Syntax

public int indexOf(int ch, int fromIndex)

Parameters

  • ch βˆ’ The character to search for in the string
  • fromIndex βˆ’ where to start the search from

Return Value

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or -1 if the character does not occur.

  • int indexOf(String str) βˆ’ Returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned.

Syntax

int indexOf(String str)

Parameters

Str – The string to search for

Return Value

Returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned.

  • int indexOf(String str, int fromIndex) βˆ’ Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned.

Syntax

int indexOf(String str, int fromIndex)

Parameters

str – The string to search for

  • fromIndex – where to start the search from

Return Value βˆ’ Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned.

Following is an example of the usage of all 4 method variants

class Example { 
   static void main(String[] args) { 
      String a = "Hello World"; 
		
      // Using public int indexOf(int ch) 
      println(a.indexOf('e')); 
      println(a.indexOf('o')); 
		
      // Using public int indexOf(int ch, int fromIndex) 
      println(a.indexOf('l',1)); 
      println(a.indexOf('e',4));
		
      // Using public int indexOf(string str) 
      println(a.indexOf('el')); 
      println(a.indexOf('or')); 
		
      // Using public int indexOf(string str,int fromIndex) 
      println(a.indexOf('el',1)); 
      println(a.indexOf('or',8)); 
   } 
}

When we run the above program, we will get the following result βˆ’

1 
4 
2 
-1 
1 
7 
1 
-1

Previous Page:-Click Here

This Post Has 2 Comments

Leave a Reply