Checkout for Promo Codes

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


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.

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 : "
        System.out.println("First occurance of String \"this\" from 6th index onwards: "

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
Different types of Access Modifiers
public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can't be seen outside of its class.

protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.

default modifier: Can be accessed only to classes in the same package.
Famous Quotations
Millions long for immortality who do not know what to do with themselves on a rainy Sunday afternoon.
-- Susan Erz

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 © 2020 by Nataraja Gootooru. All Rights Reserved.