[英]Split CSV and store in different arrays in java
My input string is of the format 我的输入字符串的格式
12.8478746,77.6632938,5:20:38 PM
12.8478746,77.6632938,5:20:49 PM
12.8478746,77.6632938,5:40:05 PM
................................
12.8478746,77.6632938,5:40:14 PM
Number of rows is unknown. 行数未知。 I need to parse the string and store it like (double lat,double long,string time). 我需要解析字符串并将其存储为(双纬度,双倍长,字符串时间)。 Also, I need to make a function call, with (lat,long,time) as arguments, 'n' times where n depends on number of rows of input string . 另外,我需要使用(lat,long,time)作为参数进行函数调用,其中n取决于输入string的行数'n'次。 How do I do this. 我该怎么做呢。
This is what I tried: 这是我尝试的:
String[] lines = result.split("\\s+"); // split on new lines
for (int i = 0; i < lines.length; i++) {
String[] temp = lines[i].split("\\s*,\\s*");
double lat = Double.parseDouble(temp[0]);
double lo = Double.parseDouble(temp[1]);
AddMarker(lat,lo,temp[2]);
}
This wont work because in "5:20:38 PM" there is a space between 5:20:38 and PM and in my input each row is separated by a space. 这是行不通的,因为在“ 5:20:38 PM”中5:20:38和PM之间有一个空格,在我的输入中,每一行都用空格隔开。 So, I'm getting the error: Invalid double "PM" 所以,我得到了错误:无效的双“ PM”
What you need to do is to work differently with split , it should accept the the separator character, don't treat it as a regular expression: 您需要做的是使用split进行不同的工作,它应该接受分隔符,不要将其视为正则表达式:
String[] lines = result.split("\n"); // split on new lines
Or possibly: 或可能:
String[] lines = result.split("\r\n");
And also: 并且:
String[] temp = lines[i].split(",");
If you want to store the date & time ("5:20:38 PM") as string, then just pass temp[2] as you already do. 如果要将日期和时间(“ 5:20:38 PM”)存储为字符串,则只需像已经进行的那样传递temp [2]。 If you want to parse as DateTime or something like that, see this link . 如果要解析为DateTime或类似的内容,请参见此链接 。
You should use a regex. 您应该使用正则表达式。 Example : 范例:
final String regex = "(.*),(.*),(.*)";
final String string = "12.8478746,77.6632938,5:20:38 PM";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
matcher.find();
double lat = Double.valueOf(matcher.group(1));
double lo = Double.valueOf(matcher.group(2));
String time = matcher.group(3);
System.out.println("LAT: "+lat);
System.out.println("LO: "+lo);
System.out.println("TIME: "+time);
Result : 结果:
LAT: 12.8478746
LO: 77.6632938
TIME: 5:20:38 PM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.