String类和字符串比较和String字符串的常用方法
1,String类又称作不可变字符序列
2,String类位于Java.lang包中,Java程序默认导入Java.lang包下的所有类
3,Java字符串就是Unicode字符序列
4,Java没有内置的字符串类型,而是在标准Java类库中提供了一个预定义的类String,每个用双引号括起来的字符串都是有String类的一个实例
package cn.com.qq;
public class TestString {
public static void main(String[] args) {
String str = "zxc";
String str2 = new String("vbn");
String str3 = "zxc"+"vbnm";
String str4 = "12"+13;// 字符串的拼接
System.out.println(str4);
System.out.println("========");
String str5 = "xiaohong";
String str6 = "xiaohong";
String str7 = new String("xiaohong");
System.out.println(str5 == str6); //比较的是是不是同一个对象,也就是比较的是不是同一个地址
System.out.println(str6 == str7);
}
}
String字符串的一些常用方法
package cn.com.qq;
public class TestString2 {
public static void main(String[] args) {
String s1 = "hello Java";
String s2 = "Hello Java";
//提取下标位2的字符
System.out.println(s1.charAt(2));
//需要注意的是容易出现数组越界异常,也就是IndexOutOfBoundsException
//字符串的长度
System.out.println(s2.length());
//比较两个字符串的内容是否相等
System.out.println(s1.equals(s2));
//比较两个字符串(忽略大小写)
System.out.println(s1.equalsIgnoreCase(s2));
//字符串s1中是否包含Java,返回出现的第一个字符的下标的位置,没有返回-1
System.out.println(s1.indexOf("Java"));
System.out.println(s2.indexOf("java"));
//将s1中的空格替换成& 需注意的是s是不可变字符序列
String s = s1.replace(" ","&");
System.out.println(s);
System.out.println("======");
System.out.println(s1);
}
}
package cn.com.qq;
public class TestString3 {
public static void main(String[] args) {
String s = "";
String s2 = "How are you?";
//是否是以其中的字符开头的
System.out.println(s.startsWith(""));
System.out.println(s.startsWith("How"));
System.out.println(s2.startsWith("How"));
//是否是以其中的字符结尾的
System.out.println(s.endsWith(""));
System.out.println(s2.endsWith("you"));
System.out.println(s2.endsWith("?"));
//提取子字符串,从下标为3 的开始到字符串结尾为止[]
s = s2.substring(3);
System.out.println(s);
//提取字符串,下标从[2,9),不包括9
s = s2.substring(2,9);
System.out.println(s);
//转小写
s = s2.toLowerCase();
System.out.println(s);
//转大写
s = s.toUpperCase();
System.out.println(s);
//去除字符串首尾的空格,中间的空格不能去
String s3 = " How old are you? ";
s = s3.trim();
System.out.println(s);
System.out.println(s3);
}
}