[To advertise Java(tm) Events here, contact us!]

by example!

New @

  gb  In-house search engine for better results!

  gb  Get updates with the

 Browse Categories 
 Ask a Java Question 
  For Java Tips & Tricks, subscribe to the newsletter!
Search Java Q&A, Links, API's:   adv 

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!

Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.