【问题标题】:How to split a string without loosing any of its chars [duplicate]如何在不丢失任何字符的情况下拆分字符串[重复]
【发布时间】:2014-06-11 06:24:27
【问题描述】:

我从文件“..1..3”中读取了这段文本,想使用 split() 进行拆分,这样我就可以得到 字符串[] = {".", ".", "1"...};但由于某种原因,我失去了我的 3 并获得了“”

【问题讨论】:

  • 你是怎么做到的?
  • 请问您能否具体说明一下您的输入/所需输出?
  • 使用 Java 8,split("") 可以正常工作。

标签: java split


【解决方案1】:

您将需要使用 split() 函数。这就是你所发现的。 但是你可以这样做:

"cat".split("(?!^)");

它会产生这个:

array ["c", "a", "t"]

来源:Split string into array of character strings

【讨论】:

  • 谢谢,("(?!^)") 部分是我正在寻找的 :)。再次感谢
【解决方案2】:

您可以尝试这样做:

public static void main(String[] args) {
    String sample = "Split me if you can";
    String[] parts = Arrays.copyOfRange(sample.split(""), 1, sample.length() + 1);
}

输出:

[S, p, l, i, t,  , m, e,  , i, f,  , y, o, u,  , c, a, n]

【讨论】:

    【解决方案3】:

    split() 方法不会丢失任何内容,请检查您如何将文件读入String(注意字符编码,不要忘记最后一个char

    你的

    【讨论】:

    • 它抛出了分隔符。
    【解决方案4】:

    试试这个:

    String s = "..1..3";
    String[] trueResult = new String[s.length()];
    System.arraycopy(s.split(""), 1, trueResult, 0, s.length());
    System.out.print(Arrays.toString(trueResult));
    

    输出:

    [., ., 1, ., ., 3]

    【讨论】:

      【解决方案5】:

      如果你想按字符分割字符串,为什么不使用

      char[] chars = mystring.toCharArray();
      

      ?

      如果你真的需要它作为字符串数组,添加:

      String[] strings = new String[chars.length];
      for (int i = 0; i < chars.length; ++i) {
          strings[i] = String.valueOf(chars[i]);
      }
      

      【讨论】:

      • 他已经提到要使用 split() 进行拆分
      • 但是为什么呢?我看不出将正则表达式机制带入如此简单的任务中的意义。
      • +1,IMO,这也是一个很好的选择,除了你得到一个字符数组而不是字符串数组。
      猜你喜欢
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 2020-04-09
      • 2015-08-31
      • 2013-04-10
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多