-2

私は正規表現について多くのことを検索しましたが、最終的に文字列を分割するために「\\s+」を使用する方が良いことがわかりました。
しかし驚くべきことに、元の文字列には何もしません:

private static void process(String command) {
    command = command.substring(0, command.length() - 1);
    String[] splitted = command.split("\\s+");
    for (String str : splitted) {
        System.out.println(str);
    }
}  

サンプル入力:

Boolean b = new Boolean(true);  

優先出力:

[Boolean,b,=,new,Boolean(true)]  

しかし、私のメソッドの出力は次のとおりです。

Boolean b = new Boolean(true)
4

1 に答える 1

2

その「優先出力」が必要な場合は、を使用しますArrays.toString(splitted)。ただし、コードは想定どおりに機能します。配列の各要素を新しい行に出力します。したがって、このコード:

  private static void process(String command) {
    command = command.substring(0, command.length() - 1);

    String[] splitted = command.split("\\s+");

    for (String str : splitted) {
      System.out.println(str);
    }

    System.out.println(Arrays.toString(splitted).replace(" ", ""));
  }

  public static void main(String[] args) {
    process("Boolean b = new Boolean(true); ");
  }

この出力を生成します:

Boolean
b
=
new
Boolean(true);
[Boolean, b, =, new, Boolean(true);]

substring入力文字列の末尾にスペースがあるため、操作が希望どおりに機能しないことに注意してください。事前に使用command.trim()して、先頭/末尾のスペースを取り除くことができます。

編集

Arrays.toString@Tim Benderが言うように、出力の配列要素の間にスペースがあり、それがOPが望んでいたものではないため、コードを編集しました。

于 2012-05-02T18:22:56.257 に答える