|
Java™ by example!
|
|
|
How do I find the first occurrence of a character or String in another String?
Use the method indexOf which will return the index as an int. If there is more than one occurrence in the target String, indexOf will return the index of the first occurrence. The function will return -1 if the String you are looking for does not exist within the String.
Remember, Java Strings are zero based!
 public class TestProg { public static void main(String args[]) { String s = "Hello, World!"; System.out.println(s.indexOf("Hello")); // prints out 0 System.out.println(s.indexOf("o")); // prints out 4 System.out.println(s.indexOf('h')); // prints out -1 } }
|
Further Information
Author of answer: unknown
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|