Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leading and trailing whitespace from the string in Java?

I want to remove the leading and trailing whitespace from string:

String s = "          Hello World                    ";

I want the result to be like:

s == "Hello world";
like image 614
user1037552 Avatar asked Feb 02 '12 07:02

user1037552


4 Answers

 s.trim()

see String#trim()

Without any internal method, use regex like

 s.replaceAll("^\\s+", "").replaceAll("\\s+$", "")

or

  s.replaceAll("^\\s+|\\s+$", "")

or just use pattern in pure form

    String s="          Hello World                    ";
    Pattern trimmer = Pattern.compile("^\\s+|\\s+$");
    Matcher m = trimmer.matcher(s);
    StringBuffer out = new StringBuffer();
    while(m.find())
        m.appendReplacement(out, "");
    m.appendTail(out);
    System.out.println(out+"!");
like image 146
Nishant Avatar answered Nov 17 '22 00:11

Nishant


String s="Test "; 
s= s.trim();
like image 3
Pratik Patel Avatar answered Nov 16 '22 22:11

Pratik Patel


I prefer not to use regular expressions for trivial problems. This would be a simple option:

public static String trim(final String s) {
    final StringBuilder sb = new StringBuilder(s);
    while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0)))
        sb.deleteCharAt(0); // delete from the beginning
    while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1)))
        sb.deleteCharAt(sb.length() - 1); // delete from the end
    return sb.toString();
}
like image 2
xehpuk Avatar answered Nov 16 '22 22:11

xehpuk


Use the String class trim method. It will remove all leading and trailing whitespace.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

like image 1
T.Ho Avatar answered Nov 16 '22 23:11

T.Ho