String类-字符串(区别于String Buffer类)
版权声明:本文为博主原创文章,转载请注明出处。
https://mp.csdn.net/mdeditor/84348483#
注意事项:
- String类用来创建字符串常量
- 字符串的值在创建后不能更改
- String对象可共享
String类的常用方法:
1、比较:
1.1 boolean equals(Object anObject):将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。
1.2 int compareTo(String anotherString):比较两个字符串是否一致。返回值为0,一致;返回值<0,当前字符串小于参数字符串;返回值>0,当前字符串大于参数字符串。
1.3 boolean contentEquals(StringBuffer sb):将此字符串与指定的 StringBuffer 比较。当且仅当此 String 与指定 StringBuffer 表示相同的字符序列时,结果才为 true。
1.4 boolean equalsIgnoreCase(String anotherString) :将此 String 与另一个 String 比较,不考虑大小写。
1.5 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) : 测试两个字符串区域是否相等。
2、判断:
2.1 boolean isEmpty() :当且仅当 length() 为 0 时返回 true。
2.2 boolean startsWith(String prefix) :测试此字符串是否以指定的前缀开始。
2.3 boolean startsWith(String prefix, int toffset) :测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
2.4 boolean endsWith(String suffix) :测试此字符串是否以指定的后缀结束。
3、转换:
3.1 char[] toCharArray() :将此字符串转换为一个新的字符数组。
3.2 String toLowerCase() :使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
3.3 String toLowerCase(Locale locale) :使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
3.4 String toUpperCase() : 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
3.5 String toUpperCase(Locale locale) :使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
替换:
3.6 String replace(char oldChar, char newChar) :返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
4、跟字符数组有关的方法
4.1 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) :将字符从此字符串复制到目标字符数组。
4.2 char[] toCharArray() :将此字符串转换为一个新的字符数组。(重复)
5、返回字符出现位置
第一次出现位置:
5.1 int indexOf(int ch) :返回指定字符在此字符串中第一次出现处的索引。
5.2 int indexOf(int ch, int fromIndex) :返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
5.3 int indexOf(String str) :返回指定子字符串在此字符串中第一次出现处的索引。
5.4 indexOf(String str, int fromIndex) :返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
最后一次出现位置:
5.5 int lastIndexOf(int ch) :返回指定字符在此字符串中最后一次出现处的索引。
5.6 int lastIndexOf(int ch, int fromIndex) :返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
5.7 int lastIndexOf(String str) :返回指定子字符串在此字符串中最右边出现处的索引。
5.8 int lastIndexOf(String str, int fromIndex) :返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
5.9 int offsetByCodePoints(int index, int codePointOffset) :返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。
6、对字符串本身的操作
6.1 String concat(String str) :将指定字符串**连接**到此字符串的结尾。
6.2 String toString() :返回此对象本身(它已经是一个字符串!)。
6.3 String trim():返回字符串的副本,去掉字符串前面和后面的空格。
6.4 int length() :返回此字符串的长度。
6.5 int hashCode() :返回此字符串的哈希码。
7、与正则表达式有关的操作
7.1 boolean matches(String regex) :告知此字符串是否匹配给定的正则表达式。
7.2 String replaceAll(String regex, String replacement) : 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
7.3 String replaceFirst(String regex, String replacement) :使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
7.4 String[] split(String regex) :根据给定正则表达式的匹配**拆分**此字符串。
7.5 String[] split(String regex, int limit): 根据匹配给定的正则表达式来**拆分**此字符串。