Here, I am sharing you another basic technique about java where I have searched a word in a String and then replace it by another word. In this technique I have avoided case differences (avoiding upper case or lower case letter difference). From this example you will be able to know about
- How to search any specific word in a string
- How to avoid case difference while searching a word in a string using java
- How to replace any specific word ignoring case difference.
Here is the code example:
class IgnoreCaseDemo {
public static void main(String args[]) {
String str = “This is Just a TEST.”;
System.out.println(“********************************”);
System.out.println(“\nHere Case is Ignored while searching.\n\n” +” Now Looking for ‘test’ in: ” + str);
// Use matches() to find any version of test.
if(str.matches(“(?i).*test.*”))
System.out.println(“\n\n ‘test’ is matched /found in the string.”);
str = “alpha beta, Alpha beta, alPHa beta, ALPHA beta”;
// Use replaceAll() to ignore case when replacing one
// substring with another.
// In this example, replace all versions of alpha with zeta.
System.out.println(“\nActual String :” + str);
System.out.println(“\n\nIgnore case when replacing.\n” + “Replace any version of ‘alpha’ ” +”with ‘zeta’ in:\n” + ” ” + str);
String result = str.replaceAll(“(?i)alpha”, “zeta”);
System.out.println(“\n\nAfter replacement:\n” + ” ” + result);
System.out.println(“********************************”);
}
}
You should take part in a contest for one of the best blogs on the web. I’ll suggest this website!
LikeLike