Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to replace all occurrences of a word in a string with another word in java?
The replaceAll() method of the String class accepts two strings, One representing a regular expression to find a string and the other representing a replacement string.
And, replaces all the matched sequences with the given String. Therefore, to replace a particular word with another in a String −
Get the required String.
Invoke the replace all method on the obtained string by passing, a regular expression representing the word to be replaced (within word boundaries “\b”) and a replacement string as parameters.
Retrieve the result and print it.
Example
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReplacingWords {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("D://sample.txt"));
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append("
"+input);
}
String contents = sb.toString();
System.out.println("Contents of the string: "+contents);
contents = contents.replaceAll("\bTutorials point\b", "TP");
System.out.println("Contents of the string after replacement: ");
System.out.println(contents);
}
}
Output
Contents of the string: Tutorials point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At Tutorials point we provide high quality learning-aids for free of cost. Tutorials point recently developed an app to help students from 6th to 12th. Contents of the string after replacement: TP originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At TP we provide high quality learning-aids for free of cost. TP recently developed an app to help students from 6th to 12th.
Advertisements