Tuesday, March 2, 2010

Remove Line Breaks From a Java String

Following code snippet shows how to remove line termination characters from a String.


import java.util.regex.*;

public class ClassA {
public static void main(String args []) {
String inputText = "sdfsdfsf\nsdfsdfsd";
String inputText2 = "var trpListenerGr\naphDivId = #trpLi\nstenerGraph2\n";
RemoveLineTerminationCharacterss(inputText);
System.out.println("-------------------------------");
RemoveLineTerminationCharacterss(inputText2);

}

public static String RemoveLineTerminationCharacterss(String inputText){
Pattern p;
Matcher m;
System.out.println(" Input Text : " + inputText);
p = Pattern.compile("\n");
m = p.matcher(inputText);
String str = m.replaceAll("");
System.out.println(" OUtput Text: " + str);
return str;
}
}

3 comments:

Troy W said...

Good post, it helped me solve a problem I've been working on for a little while. Thanks!

Ramya said...

Thanks a lot . It worked.

Heshan Suriyaarachchi said...

I'm Glad that you found it helpful.

Thanks,
Heshan.