Java Basic Problems

Java String Manipulation: How to search or match any given word in a string and then replace that word

search a word in a string and then replace javaHere, 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

  1. How to search any specific word in a string
  2. 

  3. How to avoid case difference  while searching a word in a string using java
  4. 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(“********************************”);

}

}

1 thought on “Java String Manipulation: How to search or match any given word in a string and then replace that word”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s