【问题标题】:How do I replace the commas in my string without affecting the commas in my CSV file?如何在不影响 CSV 文件中的逗号的情况下替换字符串中的逗号?
【发布时间】:2019-03-04 08:53:31
【问题描述】:

我有一个使用字符串加载的数据集,它包含如下内容:

"10, 14, 15, "20,152", 37, "42,167", 22"

如何使用Java解析数据,使引号内的逗号安全删除,其他逗号不受影响?

【问题讨论】:

  • 您需要正确对待引号,因为它包含了一个列值。这是相当微不足道的。
  • 正确对待引号是什​​么意思?

标签: java string parsing comma


【解决方案1】:

假设您想保留引号,这样的事情会起作用。如果没有,那么您可以稍微编辑一下以删除引号。

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?
【解决方案2】:

试试这个:

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);
        }
    }

}

【讨论】:

    猜你喜欢
    • 2011-02-26
    • 2019-07-05
    • 1970-01-01
    • 2018-08-06
    • 2017-12-02
    • 2019-03-24
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多