1.字符串对象操作
方法
public int length ( ) : 返回当前字符串的长度
public char charAt ( int index) : 返回在指定index位置的字符串的,index从0 开始
public boolean equals ( Object anObject) : 比较两个字符串是否相等,相等返回true ,否则返回false
public int compareTo ( String anotherString) :比较chifh
public int indexOf ( String s) : 返回s字符串在当前字符串中首次出现的位置,若没有,返回- 1
public int indexOf ( String s , int startpoint) :返回s字符串从前当前字符串startpoint位置开始,首次出现的位置。
public int lastIndexOf ( String s) : 返回s字符串最后一次出现在当前字符串的位置,若没有,返回- 1
public int lastIndexOf ( String s , int startpoint)
public boolean startsWith ( String prefix) : 判断当前字符串是否以当前字符串startWith开始
public boolean endsWith ( String suffix) : 判断当前字符串是否以当前字符串suffix结束
public boolean regionMatches ( int firstStart, String other, int otherStart , int length)
判断当前字符串从firstStart开始的字符串的子串与另一个子串other从otherStart开始,length长度的子串是否相等。
demo
@Test
public void test ( ) {
String str1 = "abcdefghijk" ;
String str2 = "bcc" ;
String str3 = "jkbcc" ;
System. out. println ( str1. length ( ) ) ;
System. out. println ( str1. charAt ( 10 ) ) ;
System. out. println ( str1. equals ( str2) ) ;
System. out. println ( str2. equals ( "abcc" ) ) ;
System. out. println ( str1. compareTo ( str1) ) ;
System. out. println ( str2. indexOf ( "cc" ) ) ;
System. out. println ( str1. lastIndexOf ( "ss" ) ) ;
System. out. println ( str1. indexOf ( "c" , 5 ) ) ;
System. out. println ( str1. lastIndexOf ( "d" , 5 ) ) ;
System. out. println ( str3. regionMatches ( 2 , str2, 0 , str2. length ( ) ) ) ;
}
2.字符串对象修改
方法
public String substring ( int startpoint) :返回从startpoint下摆开始到结束的子串
public String substring ( int start, int end) : 返回从start开始到end结束的一个左闭右开的子串,start从0 开始。
public String replace ( char oldChar, char newChar) :替换字符串
public String replaceAll ( String old, String new )
public String trim ( ) : 去除当前字符串中首位出现的空格字符
public String concat ( String str) :连接当前字符串与str
public String[ ] split ( String regex) : 按照regex将当前字符串拆分为多个字符串,整体返回String[ ]
demo
@Test
public void test3 ( ) {
String str1 = "实习生敲代码" ;
String str2 = "实习生改bug" ;
String str3 = str1. substring ( 2 ) ;
System. out. println ( str3) ;
System. out. println ( str1. substring ( 3 , 6 ) ) ;
String str4 = str1. replace ( "敲代码" , "加班" ) ;
System. out. println ( str4) ;
System. out. println ( str1) ;
String str5 = " adf dff " ;
String str6 = str5. trim ( ) ;
System. out. println ( "--" + str5+ "--" ) ;
System. out. println ( "--" + str6+ "--" ) ;
String str7 = str1. concat ( str2) ;
System. out. println ( str7) ;
String str8 = "abc*d-e7f-ke" ;
String [ ] strs = str8. split ( "-" ) ;
for ( int i = 0 ; i < strs. length; i++ ) {
System. out. print ( strs[ i] ) ;
}
}