Sunday, May 6, 2012

JAVA Manipulate a String using regular expressions

// Example 1, remove all instances of a word with another in a String.
// Example 2, remove all white spaces from a String
public static String manipulateString(String s){
  String result = s;
  
  //1 replace all instances of the word foo with the word bee 
  result = result.replaceAll("(?:foo)", "bee");

  // remove all white space
  result = result.replaceAll("\\s+", "");
   
  return result;
}

No comments:

Post a Comment