简体   繁体   English

Java分割函数读取空格后的字符为空字符串

[英]Java split function reading space after a character as an empty 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 下次需要指点

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: 您可以使用RegExp:

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

This is a Demo 这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM