Java split function reading space after a character as an empty string

Viewed 54

input: he is a good, person.

desired output: {"he","is","a","good","person"}

program output: {"he","is","a","good"," ","person"}

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        String[] ace = s.trim().split("[\\s+!,?._'@]");
        scan.close();
        System.out.println(ace.length);
        for(String c : ace)
            System.out.println(c);
    }
}

am asking for first time here. need pointers for next time

2 Answers

You have a sequence of two delimiters between "good" and "person" - a space and a comma. You could tweak your regex to allow multiple consecutive delimiter characters as the same delimiter:

String[] ace = s.trim().split("[\\s+!,?._'@]+");
// Here ------------------------------------^

You could use RegExp:

String[] words = str.split("\\W+");

This is a Demo

Related