5

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
  • 1
    Is your regex correct? Commented Sep 8, 2018 at 18:13
  • regex is for any space and these special characters !,?._'@ Commented Sep 8, 2018 at 18:14

2 Answers 2

6

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 ------------------------------------^
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. this worked .could you please tell me what that + do in the regex(i am new to programming)
@micro "+" in regex means "one or more" - so instead of the " " and the "," being treated as different delimiters, the entire sequence of ", " is treated as a single delimiter.
4

You could use RegExp:

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

This is a Demo

Comments

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.