简体   繁体   中英

Removing whitespaces and leading commas

I want to know how to remove leading whitespaces and empty string in an Array. so I want the outcome to be: line 1,line 2,line3 line4,line5

String string="line 1, line 2, , ,   line3 line4,        line 5";
        ArrayList<String> sample=new ArrayList<String>();
        sample.add(string);
        ArrayList<String> result=new ArrayList<String>();
        for (String str : sample) {
            if(str!=null && !str.isEmpty()){`enter code here`
                result.add(str.trim());
            }
        }

For this you can use a tokenizer . By additionally trim ming your strings, you only get the non-empty pieces:

StringTokenizer st = new StringTokenizer("line 1, line 2, , ,   line3 line4,        line 5", ",");
ArrayList<String> result = new ArrayList<>();
while (st.hasMoreTokens()) {
    String token = st.nextToken().trim();
    if (!token.isEmpty()) {
        result.add(token);
    }
}

I would user 2 regular expressions this way:

First, remove spaces between commas: replace ",[ ]+," by ",,". Example: "a, , , ,b" => "a,,,,b".

Then, remove duplicated commas: replace ",," by ",". Example: "a,,,,b" => "a,b".

Finally use split method (in String class) to split the string by ",". Iterate through this loop doing trim() to each token and you will get it.

This should do it:

String[] array = 
  "line 1, line 2, , ,   line3 line4,        line 5".trim().split("\\s*,[,\\s]*");

It's a simple regular expression. You want to remove all spaces before a comma, and all spaces and commas afterwards. That gives you this:

regex.Pattern(" *,[ ,]*").compile().matcher(string).replaceAll(",");

Probably you want to have the pattern precompiled in your code rather than recompiling it each time of course.

try

    Scanner sc = new Scanner(string);
    sc.useDelimiter(",\\s*");
    while(sc.hasNext()) {
        String next = sc.next();
        if (!next.isEmpty()) {
              ...
        }
    }

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