split.length 中的负 1 或其他值? (Java)

Minus 1 or another value from a split.length? (Java)

您如何从 split.length 方法中减去?您是否需要像下面的代码那样将其分配给一个 int,或者您是否必须存储 split.length 值。我想从 split.length 值中减去 1 的示例。

 String[] split  = i.split( " " );

 int a = split.length;      
 //Split method separates Char from spaces

 a -= 1;

 System.out.println("[ " + a + "]" + " Spaces in " + '"' + i + '"' );

我相信你想要的是从数组中删除最后一个元素。

我会这样做,

import java.util.Arrays;

public class Test {

    public static void main(String[] args) {
        String i = "this is a test string";
        String[] split  = i.split(" ");

        System.out.println("Before" + split.length);

        split = Arrays.copyOf(split, split.length - 1);

        System.out.println("After" + split.length);
    }

}

感谢@markspace 指点使用Arrays.copyOf

根据您的编辑,我认为您只想打印字符串中的空格数。

public class Test {

    public static void main(String[] args) {
        String i = "this is a test string";
        System.out.println("[" + (i.split(" ").length - 1) + "]" + " Spaces in \"" + i  + "\"");
    }

}

这应该可以做到。