Groovy探索 对字符串编写Groovy风格的代码
??????????Groovy探索 对字符串编写Groovy风格的代码 ? ? 本篇用来说说在处理字符串的时候的一些Groovy风格的代码,这里所说的Groovy风格的代码,主要是区别于Java语言的编码风格。 首先,我们还是要定义一个String对象,来用作我们的例子: ? ??? ? def str = "hello" ? ? 现在,我们要说的是取子串的风格。 在Java语言中,我们要取下标为1和2处的子串,就必须使用如下所示的"substring"方法: ? ??? ? println str.substring(1,3) ? 而我们在Groovy语言中,就只需如下编码: ? ??? ? println str[1..2] ? ? 运行的结果为: el ? 接着,我们想获取从下标1开始,到倒数第二位的子串,在Java语言中,我们必须如下编码: ? ??? ? println str.substring(1,str.length()-1) ? 但是,Groovy语言风格的代码却是如下形式的: ? ??? ? println str[1..-2] ? ? 运行结果为: ell ? 以上的编码风格将是在Groovy语言中我们处理字符串的基础。下面的编码风格的代码都是从这里开始的。 现在,我们来模拟在Java语言中,我们使用反射技术的时候,经常需要通过从知道的JavaBean的一个属性名获取该属性的"set"和"get"方法: ? ??? ? def propName = "email" ??? ? ??? ? def firstSetFunctionName = "set"+propName.substring(0,1).toUpperCase() ??? ? ??? ? def nextSetFunctionName = propName.substring(1,propName.length()) ??? ? ??? ? def setFunctionName = firstSetFunctionName+nextSetFunctionName ??? ? ??? ? def firstGetFunctionName = "get"+propName.substring(0,1).toUpperCase() ??? ? ??? ? def nextGetFunctionName = propName.substring(1,propName.length()) ??? ? ??? ? def getFunctionName = firstGetFunctionName+nextGetFunctionName ??? ? ??? ? println setFunctionName ??? ? ? println getFunctionName ? ? 而我们的Groovy风格的代码却是形如下面的样子: ? ??? ? ??? ? def setFunctionName = 'set'+propName[0].toUpperCase()+propName[1..-1] ??? ? ??? ? def getFunctionName = 'get'+propName[0].toUpperCase()+propName[1..-1] ? ??? ? println setFunctionName ??? ? ??? ? println getFunctionName ? ? 运行的结果为: setEmail getEmail ? ? 现在,我们有如下的一个句子: ? ??? ? def str1 = 'hello world it is a groovy world' ? ? 我们希望把这个句子的所有单词的首字母变为大写,在Java语言中个编码风格应该是下面的这个样子: ? ??? ? def list = str1.split(' ') ??? ? ??? ? def result = '' ??? ? ??? ? list.each{ ?????? ? if(it.size()>1) ?????? ? { ?????????? ? def firstStr = it.substring(0,1).toUpperCase() ?????????? ? def nextStr = it.substring(1,it.size()) ?????????? ? ?????????? ? result = result+firstStr+nextStr ?????? ? } ?????? ? else ?????? ? { ?????????? ? result = result+it.toUpperCase() ?????? ? } ?????? ? ?????? ? result = result+' ' ??? ? } ??? ? ??? ? println result ? ? ? 而我们的Groovy语言风格的代码却是如下的样子: ? ??? ? def str2 = str1.split(' ').collect{ ?????? ? it[0].toUpperCase()+(it.size()>1?it[1..-1]:'') ??? ? }.join(' ') ??? ? ??? ? println str2 ? ? ? 运行的结果为: Hello World It Is A Groovy World (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |