Wednesday, January 28, 2009

Space trimming

import java.util.regex.*;

public class BlankRemover
{

/* remove leading whitespace */
public static String ltrim(String source) {
return source.replaceAll("^\\s+", "");
}

/* remove trailing whitespace */
public static String rtrim(String source) {
return source.replaceAll("\\s+$", "");
}

/* replace multiple whitespaces between words with single blank */
public static String itrim(String source) {
return source.replaceAll("\\b\\s{2,}\\b", " ");
}

/* remove all superfluous whitespaces in source string */
public static String trim(String source) {
return itrim(ltrim(rtrim(source)));
}

public static String lrtrim(String source){
return ltrim(rtrim(source));
}

public static void main(String[] args){
String oldStr =
"> <1-2-1-2-1-2-1-2-1-2-1-----2-1-2-1-2-1-2-1-2-1-2-1-2> <";
String newStr = oldStr.replaceAll("-", " ");
System.out.println(newStr);
System.out.println(ltrim(newStr));
System.out.println(rtrim(newStr));
System.out.println(itrim(newStr));
System.out.println(lrtrim(newStr));
}
}

This program is helpful in using regular expression to beautify your string.

No comments:

Post a Comment