Java String Remove removeBlankLines(String s)

Here you can find the source of removeBlankLines(String s)

Description

remove Blank Lines

License

Apache License

Declaration

public static String removeBlankLines(String s) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static final String CRLF = "\r\n";

    public static String removeBlankLines(String s) {
        String[] lines = split(s, CRLF);
        boolean lastLineBlank = false;
        String newS = "";
        for (int i = 0; i < lines.length; i++) {
            if (!lines[i].equals("")) {
                newS += lines[i] + CRLF;
                lastLineBlank = false;/*from   w w  w .jav a  2s.  c  o  m*/
            } else {
                if (!lastLineBlank)
                    newS += CRLF;
                lastLineBlank = true;
            }
        }
        return newS;
    }

    public static String[] split(String s, String delimiter) {
        //Can't use StringTokenizer because it skips blank fields.
        //Can't use it with returnTokens because it screws up multi-char delimiters.
        //All in all, it's a pretty goddamn useless utility
        if (s.endsWith(delimiter)) {
            s += delimiter;
        }
        ArrayList<String> al = new ArrayList<String>();
        int p1 = 0, p2 = 0;
        String prev = delimiter;
        while ((p2 = s.indexOf(delimiter, p1)) != -1) {
            String fld = s.substring(p1, p2);
            if (fld.equals(delimiter) && prev.equals(delimiter)) {
                al.add("");
            } else if (!fld.equals(delimiter)) {
                al.add(fld);
            }
            prev = fld;
            p1 = p2 + delimiter.length();
        }
        if (p1 != s.length())
            al.add(s.substring(p1));
        //String rtn[] = (String[])al.toArray(new String[0]);
        //Since above line doesn't work with .NET we have to do it this way:
        String rtn[] = new String[al.size()];
        int i = 0;
        Iterator<String> iter = al.iterator();
        while (iter.hasNext()) {
            rtn[i++] = (String) iter.next();
        }
        return rtn;
    }
}

Related

  1. getAndRemove(String key)
  2. parseAndRemoveDuplicates(String s, String del)
  3. removeAll(String origStr, String removeStr)
  4. removeAll(String targetStr, String removeStr)
  5. removeAndConcatenateAlternate(String s1, String s2)
  6. removeCommandFromString(String commandString)
  7. removeEmpties(final String... values)
  8. removeEscape(String s_)
  9. removeExtraSpacesAndSpecialCharacters(String toSearch, boolean setAllToLowerCase)