String的API使用
char charAt(int index); 获取指定下标的字符
String s = "hello world" ;
char a1 = s. charAt ( 0 ) ;
System . out. println ( a1) ;
int length(); 获取长度
int len = s. length ( ) ;
for ( int i = 0 ; i < len; i++ ) {
System . out. print ( s. charAt ( i) ) ;
}
String concat(String str); 拼接 类似字符+
String a2 = s. concat ( " jack" ) ;
System . out. println ( a2) ;
System . out. println ( "hi " . concat ( "jack " ) . concat ( "how are you" ) ) ;
boolean contains(String str);判断字符串str是否存在true或false
System . out. println ( s. contains ( "hello" ) ) ;
int indexOf(String str); 获取第一次出现str的下标值0-length,如果没有出现则返回-1
常用if (str.indexOf(“xxx”) != -1) 做包含判断
System . out. println ( s. indexOf ( "he" ) ) ;
System . out. println ( s. indexOf ( "sherry" ) ) ;
int lastIndexOf(); 返回最后一次出现的xx
System . out. println ( s. lastIndexOf ( "l" ) ) ;
boolean startWith();判断是否以xx开始
System . out. println ( s. startsWith ( "hel" ) ) ;
boolean endWith();判断是否以xx结束
System . out. println ( s. endsWith ( "hel" ) ) ;
boolean equals() ; 字符串值的判断
String s1 = new String ( "hello world" ) ;
System . out. println ( s. equals ( s1) ) ;
System . out. println ( s. equals ( "sherry" ) ) ;
byte[] getBytes(charset); 字符串转字节数组
byte [ ] s3 = s. getBytes ( ) ;
for ( byte b : s3) {
System . out. print ( ( char ) b) ;
}
char[] toCharArray(); 字符串转字符数组
char [ ] s2 = s. toCharArray ( ) ;
for ( char c : s2) {
System . out. print ( c) ;
}
String[] split(regex); 按照正则,拆分数组
String s4 = "ni,hello,good,nice" ;
String [ ] s5 = s4. split ( "," ) ;
for ( String str : s5) {
System . out. println ( str) ;
}
String.join/String对象.join(符号, string[]); 把数组按照符号组合起来
String s6 = String . join ( "--" , "java" , "is" , "good" ) ;
System . out. println ( s6) ;
String replace(String old, String new); 把old换成new
String s7 = s. replace ( "hello" , "hi" ) ;
System . out. println ( s7) ;
String replaceAll(String regex, String new) 把符合正则的换成new;
String s8 = s4. replaceAll ( "," , "--" ) ;
System . out. println ( s8) ;
String substring(int beginIndex, int endIndex); [beginIndex, endIndex) 截取字符串从0开始算的
String s10 = s. substring ( 0 , 6 ) ;
System . out. println ( s10) ;
String substring(int beginIndex);截掉字符串从1开始算的
String s9 = s. substring ( 6 ) ;
System . out. println ( s9) ;
String trim(); 去除前后所有空格
String s11 = new String ( " 前后还有空格嘛 " ) ;
System . out. println ( s11. trim ( ) ) ;
String valueOf(xxxxx); 别的类型转换为String
System . out. println ( s. valueOf ( 'a' ) ) ;
System . out. println ( s. valueOf ( true ) ) ;
System . out. println ( s. valueOf ( 3.14 ) ) ;
System . out. println ( s. valueOf ( "abcdefg" ) ) ;