java
java

Reputation: 17

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

Upvotes: 0

Views: 2115

Answers (5)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try

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

Upvotes: 0

Paul Hankin
Paul Hankin

Reputation: 58221

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.

Upvotes: 0

jdb
jdb

Reputation: 4509

This should do it:

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

Upvotes: 0

Josef
Josef

Reputation: 51

For this you can use a tokenizer. By additionally trimming 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);
    }
}

Upvotes: 1

arutaku
arutaku

Reputation: 6087

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.

Upvotes: 0

Related Questions