Remove last char from string

This example will show how to remove the last character from a string in groovy. A Groovystring includes multiple techniques to drop the last char. First the getAt we create a range with the beginning index to the last element minus 2. The last two snippets substring and subSequence we pass in zero as the beginning index and length minus 1. A similar example shows how to remove last element in string in java.

getAt

@Test
void remove_last_char_with_getAt() {

    def removeString = "groovy"

    def lengthMinus2 = removeString.length() - 2

    assert "groov" == removeString.getAt(0..lengthMinus1)

    //or equivalent shorthand

    assert "groov" == removeString[0..-2]
}

substring

@Test
void remove_last_char_with_substring() {

    def removeString = "groovy"

    assert "groov" == removeString.substring(0, removeString.length() - 1)
}

subSequence

@Test
void remove_last_char_with_subSequence () {

    def removeString = "groovy"

    assert "groov" == removeString.subSequence(0, removeString.length() - 1)
}