Groovy - 检查最后一个字符&如果附加条件

时间:2014-03-22 19:48:54

标签: groovy

这是一个关于groovy的idomism问题 - 检查String的最后一个char的最简单方法是什么,如果存在则不将它附加到修改后的String?

例如在Java中你可以这样做;

String url = "http://www.google.com"

        //check to see if url already has / at the end
        if (url.charAt(url.size()-1)=='/')
            url =url + "Media"
        else
            url = "/Media"

1 个答案:

答案 0 :(得分:1)

​def url = 'http://test.com/'
url += url?.endsWith('/') ? 'Media' : '/Media'

//This should work as well but it would throw an
//ArrayIndexOutOfBoundException if url is empty ('')
//url += url[-1] == '/' ? 'Media' : '/Media'

println url​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​