【发布时间】:2019-03-04 08:53:31
【问题描述】:
我有一个使用字符串加载的数据集,它包含如下内容:
"10, 14, 15, "20,152", 37, "42,167", 22"
如何使用Java解析数据,使引号内的逗号安全删除,其他逗号不受影响?
【问题讨论】:
-
您需要正确对待引号,因为它包含了一个列值。这是相当微不足道的。
-
正确对待引号是什么意思?
我有一个使用字符串加载的数据集,它包含如下内容:
"10, 14, 15, "20,152", 37, "42,167", 22"
如何使用Java解析数据,使引号内的逗号安全删除,其他逗号不受影响?
【问题讨论】:
假设您想保留引号,这样的事情会起作用。如果没有,那么您可以稍微编辑一下以删除引号。
public String process(String input) {
StringBuilder result = new StringBuilder();
boolean insideDoubleQuotes = false;
for (char currentCharacter : input.toCharArray()) {
if (currentCharacter == '"') {
insideDoubleQuotes = !insideDoubleQuotes;
} else if (currentCharacter == ',' && insideDoubleQuotes) {
continue;
}
result.append(currentCharacter);
}
return result.toString();
}
【讨论】:
if (currentCharacter == '"') { comma = !comma; -- 这似乎没有意义。请根据其功能适当地命名您的变量。 comma 应该改为 insideDoubleQuotes。
currentCharacter == ',' && insideDoubleQuotes?
试试这个:
import java.util.ArrayList;
public class Main {
public static void main(String args[]) {
String input = "'10,11', '12,14', 15, '20,152', 37, '42,167', 22"; //
String[] list = input.split("'"); // Split the string using "'" as delimeter(change it to quotation mark)
ArrayList<String> elements = new ArrayList<>();
for (int i = 0; i < list.length; i++) {
// condition to check if it is outside/outside the quotation mark
if (i % 2 != 0) { // if inside a quotation mark
if (!list[i].trim().isEmpty()) { // so that spaces will not be included
elements.add(list[i].trim()); // add the element to the list
}
} else { //if outside the quotation marks
String[] tmp = list[i].split(","); // split the regular comma separated values
for (String s : tmp) { // iterate each splits
if (!s.trim().isEmpty()) { // check for spaces
elements.add(s.trim()); // add element to the list
}
}
}
}
for (String s : elements) {
System.out.println(s);
}
}
}
【讨论】: