Menu
Topics Index
...
`

SearchingStrings - Java Example Program


SearchingStrings
class StringSearchDemo
{
    public static void main(String arg[])
    {
        String str = "The Sun rises in the east and sets in the west.";
        System.out.println("Length of str : " + str.length());
        System.out.println("indexOf(i) : " + str.indexOf('i')); // LINE A
        System.out.println("lastIndexOf(i) : " + str.lastIndexOf('i')); // LINE B
        System.out.println("indexOf(st) : " + str.indexOf("st")); // LINE C
        System.out.println("lastIndexOf(st) : " + str.lastIndexOf("st")); // LINE D
        System.out.println("indexOf(e, 2) : " + str.indexOf('e', 2)); // LINE E
        System.out.println("lastIndexOf(e, 46) : " + str.lastIndexOf('e', 46)); // LINE F
        System.out.println("indexOf(st, 2) : " + str.indexOf("st", 2)); // LINE G
        System.out.println("lastIndexOf(st, 46) : " + str.lastIndexOf("st", 46)); // LINE H    
    }
}
OUTPUT

Length of str : 47
indexOf(i) : 9
lastIndexOf(i) : 35
indexOf(st) : 23
lastIndexOf(st) : 44
indexOf(e, 2) : 2
lastIndexOf(e, 46) : 43
indexOf(st, 2) : 23
lastIndexOf(st, 46) : 44

DESCRIPTION

LINE A is the display of index of first occurrence of character 'i'. LINE B is the display of index of last occurrence of character 'i'. LINE C is the display of index of first occurrence of substring "st". LINE Dis the display of index of last occurrence of substring "st".

LINE E is the display of index of first occurrence of character 'e' while the search starts at index 2 and continues till the end of String str. LINE F is the display of index of first occurrence of character 'e' while the search runs from index 46 to zero of String str.

LINE G is the display of index of first occurrence of substring "st" while the search starts at index 2 and continues till the end of String str. LINE H is the display of index of first occurrence of substring "st" while the search runs from index 46 to zero of String str.

THINGS TO TRY
  • Observe the output for this code.
    String str = "The Sun rises in the east and sets in the west.";
    System.out.println("indexOf(c) : " + str.indexOf('c'));
    The output for the above code : indexOf(c) -- -1
    If the passed argument character is not found in the string indexOf method returns -1.
  • Try this code
    String str = "The Sun rises in the east and sets in the west.";
    System.out.println("lastIndexOf(st, 0) : " + str.lastIndexOf("st", 0));
    System.out.println("indexOf(a) : " + str.indexOf(97));
    The output for the above code : lastIndexOf(st, 0) : -1
    indexOf(a) : 22
    lastIndexOf method searchs for the last occurence of the argument string from the passed argument index to the starting index i.e. 0, but starting index is passed as zero, so the output will become -1. for the lastIndexOf(st, 0) and indexOf(a) will return the first occurence index value of a in the string.

© meritcampus 2019

All Rights Reserved.

Open In App