1

Here is my input

....ALPO..LAPOL.STRING

I want to seperate each string when it reaches '.' and store in string array list.

I tried using the below code,

  ArrayList<String> words = new ArrayList<>    (Arrays.asList(chars.stream().map(String::valueOf)
      .collect(Collectors.joining("")).split("\\.+")));

There is a problem with regex split("\.+")) .

EXPECTED OUTPUT:

ALPO

LAPOL

STRING

ACTUAL OUTPUT:

" " - > Blank Space

LAPOL

STRING

It prints the first value of the list as an empty value because there are many '.' present before 'A". How to get rid of this empty value in string array list. Any help would be glad !!

2
  • Do you mean to say you split ....ALPO..LAPOL.STRING string? Commented May 2, 2016 at 13:48
  • Yea you can take that input as string or character array list. I have taken it as a character array list and so that code @WiktorStribiżew Commented May 2, 2016 at 13:50

1 Answer 1

5

The empty element appears because the delimiters are matched before the first value you need to get.

You need to remove the delimiter symbols from the start of the string first with .replaceFirst("^\\.+", "") and then split:

String results[] = "....ALPO..LAPOL.STRING".replaceFirst("^\\.+", "").split("\\.+");
System.out.println(Arrays.toString(results));

See the IDEONE demo

The ^\\.+ pattern matches the beginning of a string (^) and then 1 or more literal dots (\\.+). replaceFirst is used because only 1 replacement is expected (no need using replaceAll).

A bit more details on splitting in Java can be found in the documentation:

public String[] split(String regex)
Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

However, leading empty elements will be included if found. So, we first need to get rid of those delimiters at the string start.

Sign up to request clarification or add additional context in comments.

3 Comments

It works like charm..!! Could you please explain what the split("\\.+"); regex does ?@WiktorStribiżew
That is your regex actually. It just matches 1 or more literal dots (periods).
@Anusha The JavaDoc explains it very well: "When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.