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
Transient and Volatile Modifiers
Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state. Transient variables are not serialized.

Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
Famous Quotations
I respect faith, but doubt is what gets you an education.
-- Wilson Mizner

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.