Anusha
Anusha

Reputation: 969

How to split the character list when certain character is reached and store it as a string in java

Here is my character list items:

ALPO..LASS....OBO.PARROT 

The character array list of items contains a combination of '.' and letters. I want to split the characters when the last '.' is encountered and store the value as string, or pass the extracted string in String array list.

EXPECTED OUTPUT: (needed in String array list)

ALPO
LASS
OBO
PARROT

I tried using:

for (int i = 0; ....)
{
    ....
    ArrayList<Character> answerchar = new ArrayList<Character>();
    static String outputs;
    outputs += answerchar;
    outputlist.add(outputs);
}

But I am getting weird results. Any idea of what should be done?

Upvotes: 0

Views: 1082

Answers (2)

Bohemian
Bohemian

Reputation: 425263

Turn your char array into a String, then split on literal dots:

List<Character> chars; // given a list of 'A', 'L', 'P', 'O', '.', '.', 'L', 'A', 'S', 'S', etc

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

If you specifically need an ArrayList (not just any list implementation):

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

Upvotes: 3

Ajinkya Patil
Ajinkya Patil

Reputation: 741

You need to split a String with many '.' , One dot will not work, so you need to split with multiple occurrences of '.'
Try sample code of ->

String inputString = "ALPO..LASS....OBO.PARROT";
String[] stringArray = inputString.split("\\.+");
for(int i = 0; i < stringArray.length; i++){
    System.out.println(stringArray[i]);
}

Hopefully this should work.

Edit 1- It is working at my end PFA Screenshot of the same.

enter image description here

Upvotes: 1

Related Questions