简体   繁体   English

当出现空格时,在Java中用空格分割字符串?

[英]Split a string with a space in Java, when a space occurs?

I'm trying to extract data from a CSV file, in which I have the following example CSV我正在尝试从 CSV 文件中提取数据,其中有以下示例 CSV

timestamp, Column1,column2,column3
2019-05-07 19:17:23,x,y,z
2019-03-30 19:41:33,a,b,c
etc.

currently, my code is as follows:目前,我的代码如下:

public static void main(String[]args){
        String blah = "file.csv";
        File file = new File(blah);
        try{
            Scanner iterate = new Scanner(file);
            iterate.next(); //skips the first line
            while(iterate.hasNext()){
                String data = iterate.next();
                String[] values = data.split(",");
                Float nbr = Float.parseFloat(values[2]);
                System.out.println(nbr);
            }

            iterate.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
    }

However, my code is giving me an error但是,我的代码给了我一个错误

java.lang.ArrayIndexOutOfBoundsException: Index 3 is out of bounds for length 3

My theory here is the split is the problem here.我的理论是分裂是这里的问题。 As there is no comma, my program thinks that the array ends with only the first element since there's no comma on the first element (I've tested it with the timestamp column and it seems to work, however, I want to print the values in column 3)由于没有逗号,我的程序认为数组仅以第一个元素结尾,因为第一个元素上没有逗号(我已经用时间戳列对其进行了测试,它似乎有效,但是,我想打印值在第 3 栏)

How do I use the split function to get the column1, column2, and column3 values?如何使用 split 函数获取 column1、column2 和 column3 值?

import java.util.*;    
import java.util.*;     
import java.io.*;  
public class Sample  
{  
public static void main(String[] args)   
{  
String line = "";  
String splitBy = ",";  
try   
{  int i=0;
String file="blah.csv";   
BufferedReader br = new BufferedReader(new FileReader(file));    
int iteration=0;   
while ((line = br.readLine()) != null)   //returns a Boolean value  
{  if(iteration < 1) {  
  iteration++;     
  continue;}   //skips the first line
String[] stu = line.split(splitBy);    
String time=stu[3];   
System.out.println(time);   
 }   
}    
catch (IOException e)      
{     
 e.printStackTrace();    
 }} }    

Try this way by using BufferedReader通过使用 BufferedReader 尝试这种方式
Input:输入:

timestamp, Column1,column2,column3    
2019-05-07 19:17:23,x,y,z    
2019-03-30 19:41:33,a,b,c    
2019-05-07 19:17:23,x,y,a    
2019-03-30 19:41:33,a,b,f    
2019-05-07 19:17:23,x,y,x    
2019-03-30 19:41:33,a,b,y    

Output for this above code is:上面这段代码的输出是:

z   
c   
a   
f
x
y

A few suggestions:几点建议:

  1. Use Scanner#nextLine and Scanner#hasNextLine .使用Scanner#nextLineScanner#hasNextLine
  2. Use try-with-resources statement.使用try-with-resources语句。
  3. Since lines have either whitespace or a comma as the delimiter, use the regex pattern, \\s+|, as the parameter to the split method.由于行以空格或逗号作为分隔符,因此请使用正则表达式模式\\s+|,作为split方法的参数。 The regex pattern, \\s+|, means one or more whitespace characters or a comma.正则表达式模式\\s+|,表示一个或多个空白字符或逗号。 Alternatively, you can use [\\s+,] as the regex pattern.或者,您可以使用[\\s+,]作为正则表达式模式。

Demo:演示:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        String blah = "file.csv";
        File file = new File(blah);
        try (Scanner iterate = new Scanner(file)) {
            iterate.nextLine(); // skips the first line
            while (iterate.hasNextLine()) {
                String line = iterate.nextLine();
                String[] values = line.split("[\\s+,]");
                System.out.println(Arrays.toString(values));
            }
        }
    }
}

Output:输出:

[2019-05-07, 19:17:23, x, y, z]
[2019-03-30, 19:41:33, a, b, c]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM