05.0 Java Notes‎ > ‎Java: String‎ > ‎

Java String: indexOf()

find the position of the first occurrence of the string within a string



/**
* * This example show how to find the position of a character in a string.
*
*/
public void indexOfExample1()
{
    String str;
    int position;
    char COMMA = ',';

    str = "Student, Joe";


    // find the position of the first occurance of the comma in str
    position = str.indexOf(COMMA);


    // output the position and the string
    System.out.println(position);
    System.out.println(str);
}

public void indexOfExample2()
{
    String str;
    int position;
    char ch = 'z';

    str = "Student, Joe";

    // a character that is not in the string returns a -1
    position = str.indexOf(ch);

    // output the position and the string
    System.out.println(position);
    System.out.println(str);
}




Comments