A basic String handling question..I have a tokenized String like val1.val2.val3.....valN How do I get the last word valN from the string above.
To get the last word of a string:Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.
The Groovy community has added a take() method which can be used for easy and safe string truncation. Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front". Save this answer.
If you pass a negative index n to the subscript operator in a List, you get n-th last element. Therefore, the -1 element is the last one:
def words = 'val1.val2.val3' def last = words.tokenize('.')[-1] assert last == 'val3'
Update: You also have the, arguably more readable, last
method:
def last = words.tokenize('.').last()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With