1、length():获取字符串长度
String str1 = "abcde fghij";
int len = str1.length();
System.out.println(len); //返回11
2、charAt():获取某个字符
String str1 = "abcde fghij";
char c = str1.charAt(3);
System.out.println(c); //返回字符d
3、 toCharArray():将字符串变成一个字符数组
String str1 = "abcde fghij";
char[] c = str1.toCharArray();
System.out.println(c); //返回字符数组abcde fghij
System.out.println(c[3]); //返回字符d
3、concat() :连接两个字符串
String str1 = "abcde fghij";
String str2 = " abcde EGHIJ";
String str3 = str1.concat(str2);
System.out.println(str3); //返回abcde fghij abcde EGHIJ
4、trim():去掉起始和结束的空格
String str1 = " abcde fghij ";
System.out.println(str1); //返回" abcde fghij "
String str3 = str1.trim();
System.out.println(str3); //返回"abcde fghij"
5、substring():截取字符串
String str1 = "abcde fghij";
String str2 = str1.substring(3);
String str3 = str1.substring(4,7);
System.out.println(str2); //返回"de fghij"
System.out.println(str3); //返回"e f"
6、replace() 替换
String str1 = "abcde abcde";
String str2 = "你好";
String str3 = str1.replace('a','A');
String str4 = str1.replace("de","DE");
String str5 = str2.replace("你","大家");
System.out.println(str3); //返回"Abcde Abcde"
System.out.println(str4); //返回"abcDE abcDE"
System.out.println(str5); //返回"大家好"
7、equals()和equalsIgnoreCase()比较两个字符串是否相等,前者区分大小写,后者不区分
String str1 = "abcde fghij";
String str2 = "abcde FGHIJ";
System.out.println(str1.equals(str2)); //返回false
System.out.println(str1.equalsIgnoreCase(str2)); //返回true
8、startsWith()和endsWith():判断字符串是不是以特定的字符开头或结束
String str1 = "abcde FGHIJ";
System.out.println(str1.startsWith("bc")); //返回false
System.out.println(str1.endsWith("IJ")); //返回true
9、toUpperCase()和toLowerCase():将字符串转换为大写或小写
String str1 = "abcde FGHIJ";
String str2 = str1.toLowerCase();
String str3 = str1.toUpperCase();
System.out.println(str2); //返回abcde fghij
System.out.println(str3); //返回ABCDE FGHIJ
10、indexOf()和lastIndexOf()前者是查找字符或字符串第一次出现的地方,后者是查找字符或字符串最后一次出现的地方,没有则返回-1
String str1 = "abcde fgbcj";
int n1 = str1.indexOf("bc");
int n2 = str1.lastIndexOf("bc");
int n3 = str1.indexOf("dd");
System.out.println(n1); //返回1
System.out.println(n2); //返回8
System.out.println(n3); //返回-1
11、compareTo()和compareToIgnoreCase()按字典顺序比较两个字符串的大小,前者区分大小写,后者不区分,从左往右返回第一个不相同字符的asc码的差值
String str1 = "abcde fghij";
String str2 = "abcde EGHIJ";
int n1 = str1.compareTo(str2);
int n2 = str1.compareToIgnoreCase(str2);
System.out.println(n1); //返回33(f-E=102-69),asc码,e:101,f:102,E:69
System.out.println(n2); //返回1(f-e=102-101)
12、split():按照某个字符分解字符串
String str1 = "abc#de f*ghi&j";
String[] str3 = str1.split("#");
for(String st:str3){
System.out.println(st);
//输出:str3[0]=abc
//str[1]=de f*ghi&j
}
相关文章
暂无评论...