
- 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 Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to replace a substring inside a string by another one in Java
Problem Description
How to replace a substring inside a string by another one?
Solution
This example describes how replace method of java String class can be used to replace character or substring by new one.
public class StringReplaceEmp{ public static void main(String args[]){ String str = "Hello World"; System.out.println( str.replace( 'H','W' ) ); System.out.println( str.replaceFirst("He", "Wa") ); System.out.println( str.replaceAll("He", "Ha") ); } }
Result
The above code sample will produce the following result.
Wello World Wallo World Hallo World
java_strings.htm
Advertisements