有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组如何在java中分割最后一个值为空时的csv行

我有逗号分隔的值,如下所示

String s1 = "a, b, c, d, e";
String s2 = "a, , , d, ";
String s3 = "a, b, c, d, ";

我需要用“,”分开这个字符串。但是值的数量应该是5。我的意思是最后一个空值应该出现在输出数组中。 有什么解决办法吗


共 (2) 个答案

  1. # 1 楼答案

    您可以使用拆分方法:

    String[] S2 = s2.split(",");

    为了证明它有效->

    System.out.println(S2.length);
    for (String str : S2) {
         if (str.equals(" ")) {
             System.out.println("Space");
         } else {
             System.out.println(str);
    }
    
  2. # 2 楼答案

    我用绳子。split(String regex)方法,并查看数组有5个元素。我希望这能回答你的问题

    package net.javapedia.StringSplitExample;
    
    public class Main {
    
        public static void main (String[] s) {
    
            String s1 = "a, b, c, d, e";
            String s2 = "a, , , d, ";
            String s3 = "a, b, c, d, ";
            // This is the String that issue is reported
            String s4 = "a,b,c,d,";
            String s5 = "a,b,c,d,";
    
            String[] s1Array= s1.split(",");
            String[] s2Array= s2.split(",");
            String[] s3Array= s3.split(",");
            //Below split ignore empty string
            String[] s4Array= s4.split(",");
            //Below split doesn't
            String[] s5Array= s5.split(",",-1);
    
            System.out.println(s1Array.length);
            System.out.println(s2Array.length);
            System.out.println(s3Array.length);
            //Prints 4
            System.out.println(s4Array.length);
            //Prints 5 :)
            System.out.println(s5Array.length);
        }
    
    }
    

    输出:

    enter image description here

    Reference