简体   繁体   中英

Delete whitespaces in the beginning of each line and end the end of the each line

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

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]]+$", "");
}

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());

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);

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());

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM