【问题标题】:change a a list inside a string to a java String[]将字符串中的 a 列表更改为 java String[]
【发布时间】:2016-03-09 22:19:00
【问题描述】:

我有一个包含列表的字符串,我的意思是:

String list = "[\"hello\",\"everyone\"]";

如何转换它以便将其读取为String[]?我的问题可能不是很清楚,但请理解英语不是我的母语谢谢大家。

【问题讨论】:

  • 字符串看起来像 JSON —— 是吗?如果是这样,您应该使用 JSON 解析器。这样它也会为你处理字符串中的转义字符。
  • @yshavit 它实际上是一个 javascript 脚本,我将其作为字符串读取,我想从中提取此列表:/
  • JSON 是 JavaScript 的一个子集,所以如果您确定脚本只包含一个数组列表——或者如果你已经知道如何隔离脚本的子字符串——那么 JSON解析器仍然可以工作。
  • @yshavit 我会试试看谢谢你的提议:D

标签: java string list


【解决方案1】:

您可以使用String 类的replacesplit 方法来做到这一点,例如:

String s = "[\"hello\",\"everyone\"]";
String[] split = s.replace("[", "").replace("]", "").split(",");
System.out.println(Arrays.toString(split));

【讨论】:

    【解决方案2】:
    public static void main(String... args) {
            String [] strArray = new String [] {"hello","everyone"};
            System.out.println(Arrays.toString(strArray));
        }
    

    【讨论】:

      【解决方案3】:

      进口:

      import java.util.Arrays;
      import java.util.List;
      

      代码:

      public static void main(String args[]) {
          String input = "[\"hello\",\"everyone\"]"; // This is the input String
          input = input.replace("[", "").replace("]", "").replace("\\", "").replace("\"", ""); // Remove
                                                                                                  // the
                                                                                                  // following
                                                                                                  // characters:
                                                                                                  // [
                                                                                                  // ]
                                                                                                  // \
                                                                                                  // "
          String splitOn = ", "; // The string will split whenever this pattern
                                  // occurs
          List<String> output = Arrays.asList(input.split(splitOn)); // Split on
                                                                      // the
                                                                      // String
          System.out.println(output); // Output the result
      }
      

      输出:

      [hello,everyone]
      

      【讨论】:

        猜你喜欢
        • 2012-06-28
        • 2015-10-24
        • 2012-05-24
        • 2015-10-28
        • 1970-01-01
        • 2017-10-24
        • 1970-01-01
        • 2010-12-18
        • 1970-01-01
        相关资源
        最近更新 更多