String类应该是我们最常用的类之一了,我们的String类给我们提供了很多非常有用的方法,下面我们来了解一下吧
知识汇总表格
常用的方法都在这里哦
下面是敲的代码
public class TestString {
public static void main(String[] args){
String s1="I Love You";
String s2="i love you";
System.out.println(s1.charAt(1));//下标为1的字符
System.out.println(s1.length());//s1的长度
System.out.println(s1.equals(s2));//s1是否与s2相同
System.out.println(s1.equalsIgnoreCase(s2));//比较两个字符串(忽略大小写)
System.out.println(s1.indexOf("You"));//看是中是否有You返回Y的下标
System.out.println(s1.indexOf("you"));//如果没有返回-1
System.out.println(s1.replace(' ','*'));//把' '替换成*
String s = "";
String h = "How are you?";
System.out.println(h.startsWith("How"));//是否以How开头
System.out.println(h.endsWith("you"));//是否以you结尾
s = h.substring(4);//提取子字符串:从下标为4的开始到字符串结尾为止
System.out.println(s);
s = h.substring(4, 7);//提取子字符串:下标[4, 7) 不包括7
System.out.println(s);
s = h.toLowerCase();//转小写
System.out.println(s);
s = h.toUpperCase();//转大写
System.out.println(s);
String H = " How old are you!! ";
s = H.trim();//去除字符串首尾的空格。注意:中间的空格不能去除
System.out.println(s);
System.out.println(H);//因为String是不可变字符串,所以s2不变
}
}
}
}