JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

How to get index of a character or string from another String in java?


Description:

Below method shows how to get index of a specified character or string from the given string. By using indexOf() method you get get the position of the sepcified string or char from the given string. You can also get the index strting from a specified position of the string.


Code:
package com.myjava.string;

public class MyStringIndexOf {

    public static void main(String[] a){
    
        String str = "Use this string for testing this";
        System.out.println("Basic indexOf() example");
        System.out.println("Char 's' at first occurance: "+str.indexOf('s'));
        System.out.println("String \"this\" at first occurance: "+str.indexOf("this"));
        /**
         * Returns the first occurance from specified start index
         */
        System.out.println("First occurance of char 's' from 4th index onwards : "
							+str.indexOf('s',4));
        System.out.println("First occurance of String \"this\" from 6th index onwards: "
							+str.indexOf("this",6));
        
    }
}

Example Output

Basic indexOf() example
Char 's' at first occurance: 1
String "this" at first occurance: 4
First occurance of char 's' from 4th index onwards : 7
First occurance of String "this" from 6th index onwards: 28

Other String Function Examples

Knowledge Centre
What is fail-fast in java?
A fail-fast system is nothing but immediately report any failure that is likely to lead to failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators. Incase, you have called iterator on a collection object, and another thread tries to modify the collection object, then concurrent modification exception will be thrown. This is called fail-fast.
Famous Quotations
Tomorrow is often the busiest day of the week.
-- Spanish Proverb

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.