1

I have a string like this :

Mr Moh Jo\n
Address\n
 33333 City\n\n
Aland Islands

and I would like to delete whitespaces in the beginning of each line and end the end of the each line with following code but it didn't work

    public static String trimWhiteSpaceFromTheBeginingAndEndOFTheLine(
        String string) {
    Pattern trimmer = Pattern.compile("^\\s+|\\s+$");
    Matcher m = trimmer.matcher(string);
    StringBuffer out = new StringBuffer();
    while (m.find())
        m.appendReplacement(out, "");
    m.appendTail(out);

    return out.toString();
}

Expected result:

Mr Moh Jo\n
Address\n
33333 City\n\n
Aland Islands
molwiko
  • 323
  • 1
  • 6
  • 14
  • 1
    Possible Duplicate http://stackoverflow.com/questions/6652687/strip-leading-and-trailing-spaces-from-java-string – newuser Oct 09 '13 at 10:14
  • Possible Duplicate of a http://stackoverflow.com/questions/6652687/strip-leading-and-trailing-spaces-from-java-string duplicate of http://stackoverflow.com/questions/3796121/trim-whitespace-from-a-string :P – codeMan Oct 09 '13 at 10:20

5 Answers5

5

Just enable multiline flag in the regex.

Pattern.compile("(?m)^[\\s&&[^\\n]]+|[\\s+&&[^\\n]]+$");

Bam. Done.

You can also replace all that matcher code with replaceAll call:

public static String trimWhiteSpaceFromTheBeginingAndEndOFTheLine(
    String string) {
    return string.replaceAll("(?m)^[\\s&&[^\\n]]+|[\\s+&&[^\\n]]+$", "");
}
RokL
  • 2,663
  • 3
  • 22
  • 26
  • the code trimo the line break for example if have two line breaks between the city and Aland Islands the two empty line are trim which is not what I want only trim spaces not \n\n or \n – molwiko Oct 09 '13 at 11:21
  • Hm, it works with one `\n`, but `\n\n` breaks it. Seems to be a bug with java regexes. Oh wait, \n are in \s too. – RokL Oct 09 '13 at 11:40
  • 2
    @Molwiko Fixed the expression – RokL Oct 09 '13 at 11:48
  • Some other regex magic is also going on at http://stackoverflow.com/q/4123385/873282 – koppor Dec 08 '16 at 07:43
2

why not use, it exactly does what u want

 String.trim()

You could do something like this :

String address = 
"Mr Moh Jo \n" + 
"Address \n" +
" 33333 City \n" +
"Aland Islands \n";

String [] addrLines = address.split("\n");
StringBuffer formatedAddress = new StringBuffer();

for(String line : addrLines)
{
    formatedAddress.append(line.trim()+ "\n");
}

System.out.println("formatedAddress: ");
System.out.println(formatedAddress.toString());
codeMan
  • 5,730
  • 3
  • 27
  • 51
  • 2
    `String.trim()` doesn't trim whitespace from the beginning of lines in a multi-line String. – Anthony Grist Oct 09 '13 at 10:15
  • 2
    1. `formatedAddress.append(line.trim()+ "\n")` Why are you nesting string concatenation and allocating new StringBuffer each line? This line compiles to `formatedAddress.append(new StringBuilder(line.trim()).append("\n").toString())` 2. StringBuffer is a synchronized (and far slower) version of StringBuilder. You shouldn't use stringbuffer unless you want to share the object across multiple threads. – RokL Oct 09 '13 at 12:04
  • 1
    @UMad well... I was going to use StringBuilder but then I thought I am not sure if this code needs to be sync... So I thought I better use StringBuffer. And to address your first point, I dint know thats how it is interpreted. – codeMan Oct 09 '13 at 12:08
  • 1
    That's how java does string concatenation. You should just say: `formattedAddress.append(line.trim()).append('\n');`. The code doesn't need to be synced if the stringbuilder is created inside the method and never leaves the method, since every thread calling the method works with a separate instance. – RokL Oct 09 '13 at 12:14
  • @UMad could you please point me to some links to know more about how the StringBuilder.append(line.trim()+ "\n"); works? – codeMan Oct 09 '13 at 12:28
  • 1
    `http://stackoverflow.com/questions/2721998/how-java-do-the-string-concatenation-using` Read the answer with 18 upvotes (not the accepted one with 8 upvotes). If you have a `StringBuilder` already use the append method instead of using `+`. – RokL Oct 10 '13 at 08:06
0

Try this :

 String s = "Your multi line string";
      System.out.println(s);

      String[] splitString = s.split("\n");
      s="";

      for(int i =0;i<splitString.length;i++)
      {
          splitString[i]  = splitString[i].trim();
          s+=splitString[i]+"\n";

      }
      System.out.println(s);
Aneesh
  • 1,703
  • 3
  • 24
  • 34
0

Your input is a single String. so trim() only omit the initial and end whitespaces, not in between. So split the string by lineBreak. and trim() all the seperate values.

       String[] inputArray = sample.split("\n");
       StringBuilder stringBuilder = new StringBuilder();
       for(String value : inputArray)
       {
           stringBuilder.append(value.trim());
           stringBuilder.append("\n");
       }
        System.out.println("Sample : "+stringBuilder.toString());
newuser
  • 8,338
  • 2
  • 25
  • 33
0

Something like this?

private void doTrim(String str) throws Exception {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = new BufferedReader(new StringReader(str));
    String line;
    String NL = System.getProperty("line.separator");
    while( (line=reader.readLine())!=null ) {
        sb.append(line.trim());
        sb.append(NL);
    }
    System.out.println(">>" + str + "<<");
    str = sb.toString().trim();
    System.out.println(">>" + str + "<<");
}

Or hardcore version to loop string characters and update new buffer. This will trim trailing windows "\r\n" to unix "\n" newline. Little idxTail optimization newBuf could be avoided and only buf[] be used.

private String trimLeadingAndTrailingSpaces(String str) {
    char[] buf = str.toCharArray();
    char[] newBuf = new char[buf.length];
    int newCount=0;
    boolean isBegin=true;
    int trailingSpaces=0;
    for(int idx=0; idx<buf.length; idx++) {
        char ch = buf[idx];
        if (isBegin) {
            if (ch!=' ') {
                isBegin=false;
                newBuf[newCount]=ch;
                newCount++;
            }
        } else {
            if (ch==' ' || ch=='\r') {
                trailingSpaces++;
            } else if (ch=='\n') {
                if (trailingSpaces>0) newCount -= trailingSpaces;
                trailingSpaces=0;
                isBegin=true;
            } else if (trailingSpaces>0) {
                trailingSpaces=0;
            }
            newBuf[newCount]=ch;
            newCount++;
        }
    }
    return new String(newBuf, 0, newCount-trailingSpaces);
}
Whome
  • 10,181
  • 6
  • 53
  • 65