字符串比较
方法名称 描述 public boolean equals(Object anObject
区分大小写的比较 public boolean equalsIgnoreCase(String anotherString)
不区分大小写的比较 public int compareTo(String anotherString)
比较两个字符串的大小关系
String str1 = "hello" ;
String str2 = "Hello" ;
System . out. println ( str1. equals ( str2) ) ;
System . out. println ( str1. equalsIgnoreCase ( str2) ) ;
System . out. println ( "A" . compareTo ( "a" ) ) ;
System . out. println ( "a" . compareTo ( "a" ) ) ;
System . out. println ( "a" . compareTo ( "A" ) ) ;
System . out. println ( "AB" . compareTo ( "AC" ) ) ;
System . out. println ( "张" . compareTo ( "三" ) ) ;
字符串查找
方法名称 描述 public boolean contains(CharSequences)
判断一个字符串是否存在
String str = "helloworld" ;
System . out. println ( str. contains ( "world" ) ) ;
字符串替换
方法名称 描述 public String replace(char oldChar, char newChar )
替换所有指定的字符 public String replaceAll(String regex, String replacement)
替换所有指定的字符串(支持正则表达式) public String replaceFirst(String regex, String replacement)
替换首个内容
String str = "helloworld" ;
System . out. println ( str. replace ( 'o' , 'K' ) ) ;
System . out. println ( str. replaceAll ( "o" , "K" ) ) ;
System . out. println ( str. replaceAll ( "[a-z]" , "6" ) ) ;
System . out. println ( str. replaceFirst ( "o" , "K" ) ) ;
字符串拆分
方法名称 描述 public String[] split(String regex)
将字符串全部拆分 public String[] split(String regex, int limit)
将字符串部分拆分, 该数组长度就是 limit
的极限
String str = "hello china hello world" ;
String [ ] ans = str. split ( " " ) ;
for ( String string : ans) {
System . out. println ( string) ;
}
hello
china
hello
world
String str = "hello china hello world" ;
String [ ] ans = str. split ( " " , 3 ) ;
for ( String string : ans) {
System . out. println ( string) ;
}
hello
china
hello world
字符串截取
方法名称 描述 public String substring(int beginIndex)
从指定索引截取到结尾 public String substring(int beginIndex, int endIndex)
截取部分内容
System . out. println ( str. substring ( 5 ) ) ;
System . out. println ( str. substring ( 0 , 5 ) ) ;
字符串大小写转换
方法名称 描述 public String toUpperCase()
字符串转大写 public String toLowerCase()
字符串转小写
String str = "hello-world" ;
String str2 = str. toUpperCase ( ) ;
System . out. println ( str2) ;
String str3 = str2. toLowerCase ( ) ;
System . out. println ( str3) ;