- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to search a word inside a string in Java
Problem Description
How to search a word inside a string?
Solution
This example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1.
public class SearchStringEmp{ public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1) { System.out.println("Hello not found"); } else { System.out.println("Found Hello at index " + intIndex); } } }
Result
The above code sample will produce the following result.
Found Hello at index 0
This example shows how we can search a word within a String object
public class HelloWorld { public static void main(String[] args) { String text = "The cat is on the table"; System.out.print(text.contains("the")); } }
Result
The above code sample will produce the following result.
true
java_strings.htm
Advertisements