定义字符串:
字符串可以使用单引号(’)、双引号(”)、三引号(”””)
定义类型 | 描述 | 示例 |
空字符串 |
| ‘’ 或“” |
单引号 | 显示字符本身,不支持转义 | def age = 25 ‘age is ${age}’ ==> age is $age |
双引号 | 定义单行字符串, 支持转义 | def age = 25 “age is ${age}” ==> age is 25 |
三引号 | 可定义多行字符串,支持转义 | def age = 25 “””hello, age is ${age}””” ==> age is 25 |
2、获取字符串内容
字符串是顺序排列的字符集合,字符串索引指单个字符在字符串的位置。
索引从0开始,最大为字符串长度减1
示例: def first = ‘Hello World’ first[4] ==> o //返回索引为4的字符 first[-1] ==> d //返回最后一个字符 first[1..2] ==> el //返回索引为2、3的字符 first[1..<3] ==> el //返回索引从2开始,小于3的字符 first[4..2] ==> ool //返回索引从4到2的字符 first[4,1,6] ==> oew //f返回索引为4、1、6的字符 |
3、字符串方法
函数名称 | 说明 | 示例 |
size | 返回字符串长度 | ‘hello’.size() //返回5 |
length | 返回字符串长度 | ‘hello’.length() //返回5 |
getAt | 获取指定下标对应的字符值 | ‘Hello’.getAt(1) //返回e ‘Hello’.getAt(0..<3) //返回Hel ‘Hello’.getAt(0,2,4) //返回Hlo |
indexOf | 返回指定字符在字符串中首次出现的索引值 | ‘Hello’.indexOf(l) //返回2 |
concat | 连接两个字符串 | ‘He’.concat(‘llo) //返回Hello |
plus | 字符串相加 | 'He'. plus (' llo) //返回Hello |
compareToIgnoreCase | 按词典顺序比较两个字符串,忽略大小写 | ‘Hello’. compareToIgnoreCase(‘hello’) //返回0 不相同返回-1 |
equalsIgnoreCase | 比较两个字符串,忽略大小写,相同返回true,不同返回false | ‘Hello’. equalsIgnoreCase (‘hello’) //返回true |
endsWith | 判断是否以指定字符结尾 | ‘Hello’.endsWith(‘lo’) //返回true |
eachMatch | 判断字符串是否与指定的正则表达式匹配 | 'hello12a'.eachMatch(/\d*/) { ch -> println ch} //返回12 |
matches | 判断字符串是否匹配指定的正则表达式,匹配返回ture,不匹配返回false | 'hello'.matches(/[a-z]{5}/) //返回true |
minus | 删除字符串中指定的字符 | 'hello'.minus('lo') //返回hel |
replaceAll | 替换所有与正则表达式匹配的字符值 | 'hello'.replaceAll('l','L') //返回heLLo |
reverse | 获取当前字符串的逆序字符串 | 'hello'.reverse() //返回olleh |
split | 使用与给定的正则表达式相匹配的子字符串将字符串分割为多个字符串 | 'hello'.split('e') //返回[h, llo] |
substring | 获取当前字符串的子字符串 | 'hello'.substring(1) //返回ello 'hello'.substring(1,3) //返回el |
toLowerCase | 将字符串字符转换为小写 | 'heLLo'.toLowerCase() //返回hello |
toUpperCase | 将字符串字符转换为大写 | 'heLLo'.toUpperCase() //返回HELLO |
toDouble | 转换为Double类型 | '1'.toDouble() //返回1.0 |
toFloat | 转换为Float类型 | '1'.toFloat() //返回1.0 |
toInteger | 转换为Integer类型 | '1'.toInteger() //返回1 |
toLong | 转换为Long类型 | '1'.toLong() //返回1 |
toList | 转换为List类型 | '1234'.toList() //返回[1, 2, 3, 4] |