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 abstract class or abstract method?
We cannot create instance for an abstract class. We can able to create instance for its subclass only. By specifying abstract keyword just before class, we can make a class as abstract class.

public abstract class MyAbstractClass{

}

Abstract class may or may not contains abstract methods. Abstract method is just method signature, it does not containes any implementation. Its subclass must provide implementation for abstract methods. Abstract methods are looks like as given below:

public abstract int getLength();
Famous Quotations
We know what we are, but know not what we may be.
-- William Shakespeare

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.