Thursday, May 19, 2011

How to replace a character or a word at a given position in Java.

Lets assume that you want to replace the 7th character ("-") in following string with "*" character.
Then you can do it as below.
String s = "I*LIKE-JAVA BUT MY FRIEND LIKE .NET.";
System.out.println(s.substring(0,6) + "*" + s.substring(6 + 1));

Note that in above string there are two occurances of the word "LIKE".
If you want to replace the first occurances of the word "LIKE" with the word "LOVE" then you can do it as below.
String s = "I*LIKE-JAVA BUT MY FRIEND LIKE .NET.";
System.out.println(s.substring(0,2) + "LOVE" + s.substring(2 + 4));

Below example shows you how to remove a character at a certain position.
In this example we remove the "*" characterfrom the text.
String s = "WE*LIKE";
System.out.println(s.substring(0,2) + s.substring(3));

If you want to remove all the "*" from the string "I*LOVE*JAVA" then you can use below method.
String initialString = "I*LOVE*JAVA";
String result = "";
for (int i = 0; i < initialString.length(); i ++) {
 if (initialString.charAt(i) != '*') {
  result += initialString.charAt(i);
 }
}
System.out.println(result);

No comments:

Post a Comment