Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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

like image 565
micro Avatar asked Sep 08 '18 18:09

micro


People also ask

How do you split a string after space?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

Does split remove trailing spaces?

split("\\s*,\\s*"); Here, trim() method removes leading and trailing spaces in the input string, and the regex itself handles the extra spaces around delimiter.

Can you split an empty string?

The split() method does not change the value of the original string. If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.


2 Answers

You could use RegExp:

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

This is a Demo

like image 33
oleg.cherednik Avatar answered Nov 14 '22 23:11

oleg.cherednik


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 ------------------------------------^
like image 108
Mureinik Avatar answered Nov 14 '22 23:11

Mureinik