zsdroid
V2EX  ›  Java

Java 的 split 方法为什么要把后面的空字符串丢弃掉?

  •  
  •   zsdroid · Dec 9, 2019 · 5143 views
    This topic created in 2532 days ago, the information mentioned may be changed or developed.
    String a = "1,2,3,,,,,";
    System.out.println(a.split(",").length);//3
    
    Supplement 1  ·  Dec 9, 2019

    我知道第二个参数传-1,可以解决。

    我的意思是,这个api为什么要这样设计?就像5楼所说的,不觉得反人类吗?

    我在stackoverflow上只找到了一句话 该做法抄自Perl

    12 replies  •  2019-12-09 23:47:47 +08:00
    ymmud
    ymmud
    Dec 9, 2019
    1
    split(",", -1);
    lihongjie0209
    lihongjie0209
    Dec 9, 2019
    3
    你确定是
    这个空字符串“ ”

    还是这个空字符串 “”
    Rwing
    Rwing
    Dec 9, 2019
    4
    C# 欢迎您 :)
    https://docs.microsoft.com/zh-cn/dotnet/api/system.string.split?view=netcore-3.0#System_String_Split_System_String___System_StringSplitOptions_

    参数
    separator
    String[]
    分隔此字符串中子字符串的字符串数组、不包含分隔符的空数组或 null。
    options
    StringSplitOptions
    要省略返回的数组中的空数组元素,则为 RemoveEmptyEntries ;要包含返回的数组中的空数组元素,则为 None。
    conn4575
    conn4575
    Dec 9, 2019 via Android
    5
    java 的 split 和其他语言的很不一样,各种反直觉,不知道设计者怎么想的
    gaius
    gaius
    Dec 9, 2019
    6
    用 guava 的 splitter
    qwerthhusn
    qwerthhusn
    Dec 9, 2019
    7
    从来不用这个,而且这个方法的参数是一个正则表达式,比如"1.2.3.4".split(".")是得不到结果的,必须要 split("\\.")
    都是用 Guava 的 Splitter,可以明确指定按子串分割,按字符分割或者按正则分割。而且结果的话可以选择过滤或者不过滤空串
    lxk11153
    lxk11153
    Dec 9, 2019
    8
    感觉这个方法源码不难懂,看下就行了
    annielong
    annielong
    Dec 9, 2019
    9
    感觉挺好,不用再处理空字符,感觉用 split 的场景大多数是只要非空字符的
    ragnaroks
    ragnaroks
    Dec 9, 2019
    10
    没有 java 的反人类如何衬托出其他语言的优雅..
    watzds
    watzds
    Dec 9, 2019 via Android
    11
    很奇怪的设计,好像后面的会丢掉,前面的会留着

    ,,1,2,3,,
    watzds
    watzds
    Dec 9, 2019 via Android
    12
    @annielong 其他位置还是会有空的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1764 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 16:09 · PVG 00:09 · LAX 08:09 · JFK 11:09
    ♥ Do have faith in what you're doing.