Search code examples
javasplitstring-length

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


How would you minus from a split.length method? Would you need to assign it to an int like the code below or would you have to store the split.length value. An example I want to minus 1 from the split.length value.

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

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

 a -= 1;

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

Solution

  • I belive what you wanted was to remove the last element from the array.

    I would do it like the following,

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

    Thanks to @markspace for pointing to use Arrays.copyOf

    From your edit, I think you just want to print the no of spaces in string.

    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  + "\"");
        }
    
    }
    

    This should do it.