【问题标题】:Split Strings from an array of Strings从字符串数组中拆分字符串
【发布时间】:2016-10-09 03:55:37
【问题描述】:

我想从字符串数组中提取行,然后拆分“;”将数据存储在数组中时的分隔符。我知道这是 split 方法应该做的。但我无法通过。 我应该如何处理?

public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String LON = in.next();
        String LAT = in.next();
        int N = in.nextInt();
        in.nextLine();
        String[] infoDefib=new String[N];                                  
        for (int i = 0; i < N; i++) {
            String DEFIB = in.nextLine();
            infoDefib[i]=DEFIB.split(";");
        }
        //System.out.println();
    }

【问题讨论】:

    标签: java arrays split


    【解决方案1】:

    split 函数将拆分字符串并将它们中的每一个存储到一个字符串数组中。

    例如:String[] strs = DEFIB.split(";");

    您不必使用 for 循环并将它们单独存储到 String[] 中。新建一个 String[] 并等于 String.split("***")。 Java 会为你做这件事。

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        //String LON = in.next();
        //String LAT = in.next();        
        String str = in.nextLine(); // use nextLine which you can read whole 
                                    //line and store the data into a String
        in.nextLine();
        String[] infoDefib = DEFIB.split(";");//now you store them into a String array
    

    【讨论】:

    • 我在 for 循环中声明和初始化数组时的问题是我不知道如何将它返回到循环之外。我是 Java 新手。
    【解决方案2】:

    String 的 split() 方法非常简单。您需要将分隔符作为参数传递,它将返回一个字符串数组,其中字符串由提供的分隔符分隔。

    示例:

    String data = "This.is.simple.example.of.split.method";
    String[] splitArray = data.split(".");//period(.) being delimeter
    for (String val : splitArray) {
        System.out.println(val);
    }
    

    结果:

    This
    is
    simple
    example
    of
    split
    method
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 2021-12-12
      • 1970-01-01
      • 2012-02-22
      • 2016-04-01
      相关资源
      最近更新 更多