Java Search String Example

  1. /*
  2.   Java Search String Example
  3.   This example shows how we can search a word within a String object using
  4.   indexOf method.
  5. */
  6.  
  7. public class SearchStringExample {
  8.  
  9. public static void main(String[] args) {
  10. //declare a String object
  11. String strOrig = "Hello world Hello World";
  12.  
  13. /*
  14.   To search a particular word in a given string use indexOf method.
  15.   indexOf method. It returns a position index of a word within the string
  16.   if found. Otherwise it returns -1.
  17.   */
  18.  
  19. int intIndex = strOrig.indexOf("Hello");
  20.  
  21. if(intIndex == - 1){
  22. System.out.println("Hello not found");
  23. }else{
  24. System.out.println("Found Hello at index " + intIndex);
  25. }
  26.  
  27. /*
  28.   we can also search a word after particular position using
  29.   indexOf(String word, int position) method.
  30.   */
  31.  
  32. int positionIndex = strOrig.indexOf("Hello",11);
  33. System.out.println("Index of Hello after 11 is " + positionIndex);
  34.  
  35. /*
  36.   Use lastIndexOf method to search a last occurrence of a word within string.
  37.   */
  38. int lastIndex = strOrig.lastIndexOf("Hello");
  39. System.out.println("Last occurrence of Hello is at index " + lastIndex);
  40.  
  41. }
  42. }
  43.  
  44. /*
  45. Output of the program would be :
  46. Found Hello at index 0
  47. Index of Hello after 11 is 12
  48. Last occurrence of Hello is at index 12
  49. */

regarding java programs

i need a program
q: write a program to simulate on-line shopping?

Post new comment

To combat spam, please enter the code in the image.


Suggested Reading

Oracle Magazine
Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.
Cost: FREE

View/Subscribe
NASA Tech Briefs
Features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems.
Cost: FREE

View/Subscribe
FierceBiotech IT
Is a free, easy to read weekly email service that brings must read biotech IT news to senior biotech, pharma, and IT executives.
Cost: FREE

View/Subscribe
Simply SQL
Simply SQL is a practical step-by-step guide to writing SQL.
Cost: FREE

View/Subscribe
Simply JavaScript
Packed with full-color examples, Simply JavaScript is all you need to start programming in JavaScript the right way.
Cost: FREE

View/Subscribe
PCMag.com's What's New Now
Lance Ulanoff, Editor in Chief of the PC Magazine Network, brings you this twice-weekly roundup of the latest top tech stories, the best new product reviews, plus special offers from Ziff Davis and its partners.
Cost: FREE

View/Subscribe

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!