字符串和正则表达式
Strings, Characters and Regular Expressions
String类
构造String
1 |
|
非静态方法
s1.length()
s1.charAt(index) //输出某个指定下标的字符
s1.getChars(0, 5, charArray, 0); //将子串输出到字符数组中
s1.equals(s2) //判断是否相等
s1.equalsIgnore(s2) //忽略大小写后判断是否相等,等价于s1.toLowerCase().equals(s2.toLowerCase())
s1.compareTo(s2) //按照字典序比较字符串的大小
s1.regionMatches(0, s2, 0, 5) //局部匹配,如果前5个字符相同则返回true
s1.regionMatches(true, 0, s2, 0, 5); //局部匹配,但是忽略大小写
s1.startsWith(s2) //是否以s2开头
s1.endsWith(s2) //是否以s2结尾
s1.indexOf(char) //首个指定字符的下标,不存在则返回-1
s1.indexOf(char, i) //从第i个字符之后的首个指定字符的下标
s1.lastIndexOf(char) //末个指定字符的下标,不存在则返回-1
s1.lastIndexOf(char, i) //从第i个字符之后的末个指定字符的下标
s1.indexOf(str)
…
s1.substring(fromIndex) //从第fromIndex到最后的字符串
s1.substring(fromindex, endindex) //[fromindex, endindex)
s1.concat(s2) //连接字符串
s1.replace(‘l’, ‘L’) //取代字符串中所有的l
s1.toUpperCase()
s1.toLowerCase()
s1.trim() //去掉首尾的空格
s1.toCharArray() //字符串转换为字符数组
静态方法
- String.valueOf(charArray) //将字符数组转化为字符串
- String.valueOf(charArray, 2, 2) //输出从下标2开始长度为2的字符串
- String.valueOf(integerVal, longVal, booleanVal,…) //将基本类型转换为字符串输出
词法分析
- sentence.split(“ “) //根据空格将句子分成很多个单词,返回一个字符串数组
StringBuilder类
可修改的String
构造同String
常用方法
大部分String能用的StringBuilder都能用
- buffer.length()
- buffer.capacity()
- buffer.ensureCapacity(number)
- buffer.setLength(number)
- buffer.setCharAt(index, char)
- buffer.append(String)
- buffer.insert(index, string) //在index之前插入string
Character类
静态方法
- Character.isDefined(c) //该字符是否被定义
- Character.isDigit(c)
- Character.isJavaIdentifierStart(c) //是否是合法的Java首字符
- Character.isJavaIdentifierPart(c) //是否是合法的Java字符
- Character.isLetter(c)
- Character.isLetterOrDigit(c)
- Character.isLowerCase(c)
- Character.isUpperCase(c)
- Character.toUpperCase(c)
- Character.toLowerCase(c)
- Character.forDigit(digit, radix) //radix进制下,将数digit转换为字符
- Character.digit(character, radix) //将character转换成radix进制数
非静态方法
- c1.charValue() //转换成char
- c1.toString()
正则表达式,Pattern类和Matcher类
正则表达式
Predefined character classes
Character | Matches |
---|---|
\d | any digit |
\w | any word character |
\s | any white-space character |
\D | any nondigit |
\W | any nonword character |
\S | any non-whitespace character |
Quantifiers used in regular expressions
Quantifier | Matches |
---|---|
* | zero or more pre-character |
+ | one or more pre-character |
^ | not match character |
() | have or not have |
| | or |
d{5} | match five digits |
d{5,} | match five or more digits |
d{5,6} | match five to six digits |
? | match zero or one pre-character |
. | dot, match any singer character except a new-line character |
[] | match only-one given character |
Pattern类和Matcher类
Pattern:
用来存储一个正则表达式
声明:
1 |
|
Matcher:
既包含一个正则表达式的Pattern,也包含一个用来查找Pattern的CharSequence
声明:
1 |
|
使用方法:
1 |
|