for循环迭代-如何避免逗号

我想将字符串与“,”一起从2到6。当我执行下面的代码时,我得到了输出,但是它以逗号开头。


    String name="";

    String s = "1,two,three,four,five,six,seven"; //this is a sample string, original string might contain more words separated by ","

    String[] split = s.split(",");

    System.out.println("Splitted Length: " +split.length);

    if(split.length>2) {

        for(int i=1; i<split.length-1;i++) {

            name = name+","+split[i];

        }

    }

    System.out.println(name);

输出:


  Splitted Length: 7

 ,two,three,four,five,six

如何避免第一个逗号


慕容708150
浏览 164回答 3
3回答

DIEA

请停止使用那些for循环。不要发明新事物。知道API。List<String>&nbsp;valuesList&nbsp;=&nbsp;Arrays.asList(array).subList(x,&nbsp;y); String&nbsp;newValuesString&nbsp;=&nbsp;String.join(",",&nbsp;valuesList);

FFIVE

您可以使用Java8Stream和Pattern为。String result = Pattern.compile(",").splitAsStream(s)&nbsp; &nbsp; .skip(1)&nbsp; &nbsp; .collect(Collectors.joining(","));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java