guo_david_wei 2008-10-06 10:19
浏览 244
已采纳

String.split()方法出问题啦!!

最近碰到了一个问题,很奇怪,始终都没弄明白是怎么回事

public class Test {

public static void main(String[] args) {

String str = "2,,3,4,3,,,,,";

String[]flag = str.split(",");

System.out.println(flag.length); //为什么是 5 ???

}

}

为什么上面出现的结果会是5呢??它等于是忽略了后面的逗号,但是为什么前面的那个逗号却没忽略???

  • 写回答

6条回答 默认 最新

  • bluespring 2008-10-06 11:25
    关注

    jdk1.5 String的split方法注解

    This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. [color=red]Trailing empty strings are therefore not included in the resulting array.[/color]

    中文的
    该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,[color=red]结果数组中不包括结尾空字符串。[/color]

    [code="java"]// Construct result
    int resultSize = matchList.size();
    if (limit == 0)
    while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
    resultSize--;
    String[] result = new String[resultSize];
    return matchList.subList(0, resultSize).toArray(result);[/code]

    split方法是调用Pattern的split实现的,看上面代码中的
    while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
    resultSize--;
    可见。字符串末尾的空字符串将从匹配结果中去除

    不知楼上所云重点何在

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比