java中String类表示的字符串是不可变字符串,无法修改字符串中某个位置的值,要想修改字符串只能通过拼接返回一个新的字符串。
public class DemoString {
public static void main(String[] args) {
String str = "i_meteor_shower";
/*char charAt(int index)
*返回给定位置的代码单元(可粗略的理解为返回一个字符,但其实有些特殊码点可占用多个代码单元)
*/
System.out.println("第4个位置的字符为:" + str.charAt(3)); //返回第4个位置上的字符'e',位置从0开始计算
/*boolean equals(String other)
* 判断字符串是否与other字符串相等,先等返回true,否则返回false
* 注意'=='运算符并不能检测字符串是否相等,而是比较的地址是否相等
*/
if(str.equals("I_meteor_shower")) {
System.out.println("i_meteor_shower == I_meteor_shower");
}else {
System.out.println("i_meteor_shower != I_meteor_shower");
}
/*
* boolean equalsIgnoreCase(String other)
* 忽略大小写,然后判断字符串与other字符串是否相等
*/
if(str.equalsIgnoreCase("I_meteor_shower")) {
System.out.println("i_meteor_shower == I_meteor_shower");
}else {
System.out.println("i_meteor_shower != I_meteor_shower");
}
/*
* int indexOf(String str)
* 返回与字符串str匹配的第一个子串的开始位置索引值(从字符串开始匹配)
* int indexOf(String str, int fromIndex)
* 从fromIndex开始匹配,返回与字符串str匹配的第一个子串的开始位置
*/
System.out.println("meteor的最开始出现的位置为:" + str.indexOf("meteor"));
/*
* int lastIndexOf(String str)
* 返回与字符串str匹配的最后一个子串的开始位置索引值(从字符串尾端开始计算)
* int lastIndexOf(String str, int fromIndex)
* 从fromIndex开始计算,返回与字符串str匹配的最后一个子串的开始位置索引值
*/
System.out.println("meteor最后出现的位置为:" + str.lastIndexOf("meteor"));
/*
* int length();
* 返回字符串的长度(代码单元的长度)
*/
System.out.println("i_meteor_shower的长度为:" + str.length());
/*
* String substring(int beginIndex)
* 返回一个从beginIndex截取到结尾的新字符串,注意substring中的第二个s也是小写
* String substring(int beginIndex, int endIndex)
* 返回一个从beginIndex截取到endIndex-1的字符串
*/
System.out.println(str.substring(2, 8)); //截取meteor
/*
* String toLowerCase()
* 将原字符串中的大写字母改为小写并返回
* String toUpperCase()
* 将原字符串中的小写字母改为大写并返回
*/
System.out.println("I_meteor_shower转小写:" + "I_meteor_shower".toLowerCase());
System.out.println("I_meteor_shower转大写" + "I_meteor_shower".toUpperCase());
/*
* String trim()
* 返回一个新字符串,该字符串删除了原字符串头部和尾部的空格
*/
System.out.println("\" meteor shower \"去除前后空格:" + " meteor shower ".trim());
/*
* String join(String delimiter, String emement1, ..., String emementn)
* 返回一个新字符串,哟弄个delimiter连接了emement1到emementn
* 该方法为静态方法,可通过类名.方法名(String.join())直接调用
*/
System.out.println(String.join("_", "i", "meteor", "shower"));
}
}