String类
- String类代表字符串,提供了开发中常用的字符串处理的方法,如:求字符串的长度,截取字符串,替换字符串字符串是常量,它的值创建之后就不可以再修改了
- String类常用构造方法:
1.String()无参构造方法
2.String(String str)有一个字符串参数的构造方法
3.String(char[]ch)有一个char类型数组参数的构造方法
4.String(byte[]b)有一个byte类型数组参数的构造方法
声明和创建字符串对象的方式:
String s1="s1";
String s2=new String();
String s3="";
char[]ch=new char[] {'h','e','l','l','o'};
String s4=new String(ch);
byte[]b=new byte[] {99,100};
String s5=new String(b);
String s6="2";
String 常用方法:
public class Demo02Methods {
public static void main(String[] args) {
String s1="dfsas";
System.out.println(s1.length());
String s2="sajfio";
System.out.println(s1.equals(s2));
System.out.println(s1.replace('s', 'k'));
System.out.println(s1.replace("df", "am"));
System.out.println(s1.charAt(3));
System.out.println("hello9980".compareTo("hello9909"));
System.out.println(s2.endsWith("io"));
System.out.println(s2.startsWith("sajfio"));
System.out.println(String.valueOf(10)+5);
System.out.println(s1.isEmpty());
System.out.println("".isEmpty());
System.out.println(s1.indexOf("f"));
System.out.println("这个"+s1.indexOf("kk"));
System.out.println(s1.lastIndexOf("l"));
System.out.println(s1.substring(3));
System.out.println(s1.substring(2, 3));
}
}
compareTo方法介绍:
- 返回值是整型,它是先比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,
- 结束比较,返回他们之间的差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的
- 第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方结束。
- 如果参数字符串等于此字符串,则返回值 0;如果此字符串小于字符串参数,则返回一个小于 0 的值;
- 如果此字符串大于字符串参数,则返回一个大于 0 的值。