package com.wq.String_.String常用方法;
public class String常用方法2 {
public static void main(String[] args) {
//1. toUpperCase 转换成大写
String s = "kinG";
System.out.println(s.toUpperCase());//KING
//2. toLowerCase 转换成小写
System.out.println(s.toLowerCase());//king
//3. concat 拼接字符串
String s1 = "宝玉";
s1 = s1.concat("林黛玉").concat("薛宝钗").concat("together");
System.out.println(s1);
//4. replace 替换字符串中的字符
s1 = "宝玉 and 林黛玉 林黛玉 林黛玉";
//在s1中,将所有的 林黛玉 替换成 薛宝钗
//s1.replace() 方法执行后 返回的结果才是替换过的
//注意对s1 没有任何影响
String sss =s1.replace("林黛玉","薛宝钗");
System.out.println(s1);//没有影响啊
System.out.println(sss);//替换之后
//5.split 分割字符串 , 对于某些分割字符 , 我们需要 转义比如 | \\等
String poem = " 锄禾日当午 , 汗滴禾下土 , 谁知盘中餐 , 粒粒皆辛苦";
// 以 , 为标准对 poem 进行分割 , 返回一个数组
String []spilt = poem.split(",");
poem = "E:\\aaa\\bbb";
spilt = poem.split("\\\\");//需要四个
for (int i = 0; i < spilt.length; i++) {
System.out.println(spilt[i]);
}
//6.toCharArray 转换成字符数组
s = "kingwq";
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.print(chars[i]+" ");
}
//7. compareTo 比较两个字符串大小 如果前者大 则返回整数
//后者大 则返回负数, 如果相等 返回0
//(1) 如果长度相同 并且每个字符也相等 就返回0
//(2) 如果长度相同 或者不相同 但是在进行比较时, 可以区分大小
/*
就返回 if(c1 != c2){
return c1 - c2;
}
*/
//(3)如果前面的部分多相同 就返回 STR1.length - STR.length
String a = "kin";//length = 3
String b = "king";//length = 4
System.out.println("\n"+a.compareTo(b));//-1
}
}
结果
com.wq.String_.String常用方法.String常用方法2
KING
king
宝玉林黛玉薛宝钗together
宝玉 and 林黛玉 林黛玉 林黛玉
宝玉 and 薛宝钗 薛宝钗 薛宝钗
E:
aaa
bbb
k i n g w q
-1
Process finished with exit code 0