String
字符串:由多个字符组成的一串数据。也可以看成是一个字符数组。
通过查看API,我们可以知道
字符串字面值"abc"也可以看成是一个字符串对象
字符串是常量,一旦被赋值,就不能被改变
String的构造方法
public String():无参构造
public String(byte[] bytes):把字节数组转成字符串
public String(byte[] bytes, int index, int length):把字节数组的一部分转成字符串
public String(char[] value):把字符数组转成字符串
public String(char[] value, int offset, int count):把字符数组的一部分转成字符串
public String(String original):把字符串常量转成字符串
字符串的方法:public int length()返回字符串的长度
public class StringDemo {
public static void main(String[] args) {
String s1 = new String();
System.out.println("s1:" + s1);
System.out.println(s1.length());
System.out.println("----------");
byte[] bys = { 97, 98, 99, 100, 101 };
String s2 = new String(bys);
System.out.println("s2:" + s2);
System.out.println("s2的长度" + s2.length());
System.out.println("----------");
byte[] bys2 = { 97, 98, 99, 100, 101 };
String s3 = new String(bys2, 1, 3);
System.out.println("s3:" + s3);
System.out.println("s3的长度" + s3.length());
System.out.println("----------");
char[] chs = {'a','b','c','d','徐'};
String s4 = new String(chs);
System.out.println(s4);
System.out.println("s4的长度" + s4.length());
System.out.println("----------");
char[] chs2 = {'a','b','c','d','徐'};
String s5 = new String(chs, 2, 3);
System.out.println(s5);
System.out.println("s5的长度" + s5.length());
System.out.println("----------");
String s6 = new String("abcde");
System.out.println(s6);
System.out.println("s6的长度" + s6.length());
}
}
字符串的特点:一旦被赋值就不能被改变
内存图解:
String s = new String(“hello”)和String s = "hello"的区别?
前者会创建两个对象,后者创建一个对象
==和equals的区别:
==:比较引用类型比较的是地址值是否相同
equals:比较引用类型默认也是比较的地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同
内存图解
两个面试题
//看程序写结果
public class StringDemo3 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
String s3 = new String("hello");
String s4 = "hello";
System.out.println(s3 == s4);// false
System.out.println(s3.equals(s4));// true
String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);// true
System.out.println(s5.equals(s6));// true
}
}
//看程序写结果
/*
* 看程序写结果
* 字符串如果是变量相加,先开空间,在拼接。
* 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
*/
public class StringDemo4 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);// false
System.out.println(s3.equals((s1 + s2)));// true
System.out.println(s3 == "hello" + "world");// false 这个我们错了,应该是true
System.out.println(s3.equals("hello" + "world"));// true
// 通过反编译看源码,我们知道这里已经做好了处理。
// System.out.println(s3 == "helloworld");
// System.out.println(s3.equals("helloworld"));
}
}
String字符串的功能
String类的判断功能
boolean equal(Object obj)//比较字符串的内容是否相同
boolean equalsIgnoreCase(String str)//比较字符串的内容是否相同,忽略大小写
boolean contains(String str)//判断大串中是否包含小串
boolean startsWith(String str)//判断字符串中是否以指定的某个字符串开头
boolean endsWith(String str)//判断字符串中是否以指定的某个字符串结尾
boolean isEmpty()//判断是否为空
public class StringDemo {
public static void main(String[] args) {
//boolean equal(Object obj)//比较字符串的内容是否相同
String str1 = "helloworld";
String str2 = "helloworld";
String str3 = new String("helloworld");
System.out.println(str1.equals(str2));//true
System.out.println(str1.equals(str3));//true
System.out.println("---------------");
//boolean equalsIgnoreCase(String str)//比较字符串的内容是否相同,忽略大小写
String str4 = "helloworld";
String str5 = "HelloWorld";
String str6 = "Hello World";
System.out.println(str4.equalsIgnoreCase(str5));
System.out.println(str4.equalsIgnoreCase(str6));
System.out.println("---------------");
//boolean contains(String str)//判断大串中是否包含小串
String str7 = "helloworld";
String str8 = "owo";
System.out.println(str7.contains(str8));
System.out.println(str7.contains("llo"));//可以是定义了的字符串变量,也可以直接一串字符串
System.out.println("---------------");
//boolean startsWith(String str)//判断字符串中是否以指定的某个字符串开头
String str9 = "helloworld";
String str10 = "xwk";
System.out.println(str9.startsWith(str10));
System.out.println(str9.startsWith("he"));
System.out.println("---------------");
//boolean endsWith(String str)//判断字符串中是否以指定的某个字符串结尾
String str11 = "helloworld";
String str12 = "xwk";
System.out.println(str11.endsWith(str12));
System.out.println(str11.endsWith("fck"));
System.out.println("---------------");
//boolean isEmpty()//判断是否为空
String str13 = "helloworld";
String str14 = "";
String str15 = null;
System.out.println(str13.isEmpty());
System.out.println(str14.isEmpty());
//System.out.println(str15.isEmpty());//NullPointerException
}
}
String类的获取功能
int length()//获取字符串的长度
char charAT(int index)//获取指定索引位置的字符
为什么这里是int类型,而不是char类型?
原因是:'a'和97其实都可以代表'a'
int indexOf(int ch)//返回指定字符在此字符串中第一次出现的索引
int indexOf(String str)//返回指定字符串在此字符串中第一次出现处的索引,返回字符串第一个字符的索引
int indexOf(int ch, int fromIndex)//返回指定字符在此字符串中从指定位置后第一次出现的索引
int indexOf(String str, int fromIndex)//返回指定字符串在此字符串中从指定位置后第一次出现的索引
String substring(int start)//截取字符串,从指定位置开始截取字符串,默认到末尾包含start
String substring(int start, int end)//截取字符串,总指定位置开始到指定位置结束,包含strat不包含end
public class StringDemo {
public static void main(String[] args) {
String str = "helloworldowo";
// int length()//获取字符串的长度
System.out.println("字符串的长度是:" + str.length());
System.out.println("-----------");
//char charAT(int index)//获取指定索引位置的字符
System.out.println("索引为3的位置的字符是:" + str.charAt(3));
System.out.println("-----------");
//int indexOf(int ch)//返回指定字符在此字符串中第一次出现的索引
System.out.println("第一次出现d的位置的索引是:" + str.indexOf('d'));
System.out.println("-----------");
//int indexOf(String str)//返回指定字符串在此字符串中第一次出现处的索引,返回字符串第一个字符的索引
System.out.println("第一次出现owo的位置的索引是:" + str.indexOf("owo"));
System.out.println("-----------");
//int indexOf(int ch, int fromIndex)//返回指定字符在此字符串中从指定位置后第一次出现的索引
System.out.println("从第二个索引开始,第一次出现o的位置的索引是:" + str.indexOf('o', 5));
System.out.println("-----------");
//int indexOf(String str, int fromIndex)//返回指定字符串在此字符串中从指定位置后第一次出现的索引
System.out.println("从第二个索引开始,第一次出现owo的位置的索引是:" + str.indexOf("owo", 0));
System.out.println("-----------");
//String substring(int start)//截取字符串,从指定位置开始截取字符串,默认到末尾包含start
System.out.println("截取从2开始的字符串" + str.substring(2));
System.out.println("-----------");
//String substring(int start, int end)//截取字符串,总指定位置开始到指定位置结束,包含strat不包含end
System.out.println("截取从2开始到10结束的字符串" + str.substring(2, 10));
}
}
练习:遍历获取每一个字符
//方法一 用length()和charAt()
public class StringDemo {
public static void main(String[] args) {
String str = "helloworld";
//遍历str字符串
for(int x= 0; x<str.length(); x++){
System.out.println(str.charAt(x));
}
}
}
//方法二,把字符串转成字符数组,然后遍历字符数组
public class StringDemo {
public static void main(String[] args) {
String str = "HelloWorld";
char[]chArr = str.toCharArray();
for(int i = 0;i<chArr.length;i++){
System.out.println(chArr[i]);
}
}
}
练习:统计大写、小写及数字字符的个数
/*
* 需求:统计一个字符串中大写字母,小写字母和数字字符出现的次数
* 举例:"Hello123World"
* 结果:大写:2个
* 小写:8个
* 数字:3个
* */
public class StringDemo {
public static void main(String[] args) {
String str = "Hello123World";
int x = 0;//小写字母个数
int y = 0;//大写字母个数
int z = 0;//数字个数
for (int i = 0; i < str.length(); i++) {
if(97<str.charAt(i) &&str.charAt(i)<122){
x++;
continue;
}else if(65<str.charAt(i) &&str.charAt(i)<90){
y++;
continue;
}else if(48<str.charAt(i) &&str.charAt(i)<57){
z++;
continue;
}else{
System.out.println("不统计此字符的个数");
continue;
}
}
System.out.println("小写字母的个数是:"+x);
System.out.println("大写字母的个数是:"+y);
System.out.println("数字的个数是:"+z);
}
}
String的转换功能
byte[] gstBytes()//把字符串转换为字节数组
char[] toCharArray()//把字符串转换为字符数组
static String valueOf(char[] chs)//把字符数组转成字符串
static String valueOf(int i)//把int类型的数据转换成字符串,注:可以把任意类型的数据转换成字符串
String toLowerCase()//把字符串转成小写
String toUpperCase()//把字符串转成大写
String concat()//把字符串拼接
public class StringDemo {
public static void main(String[] args) {
String str = "HelloWorld";
//byte[] gstBytes()//把字符串转换为字节数组
byte[] byt = str.getBytes();
for(int i = 0; i < str.length(); i++){
System.out.println(byt[i]);
}
System.out.println("------------");
//char[] toCharArray()//把字符串转换为字符数组
char[] c = str.toCharArray();
for(int x = 0; x < str.length(); x++){
System.out.println(c[x]);
}
System.out.println("------------");
//static String valueOf(char[] chs)//把字符数组转成字符串
System.out.println(String.valueOf(c));
System.out.println("------------");
//static String valueOf(int i)//把int类型的数据转换成字符串,注:可以把任意类型的数据转换成字符串
System.out.println(String.valueOf(10));
System.out.println("------------");
//把字符串转成小写
System.out.println(str.toLowerCase());
System.out.println("------------");
//把字符串转成大写
System.out.println(str.toUpperCase());
System.out.println("------------");
//把字符串拼接
String str2 = "hello";
String str3 = "world";
System.out.println(str2.concat(str3));
}
}
练习:把一个字符串的首字母转成大写,其余为小写(只考虑英文大小写)
public class StringDemo {
public static void main(String[] args) {
String str = "HELLOWORLD";
String str2 = str.substring(0, 1);
String str3 = str.substring(1);
String str4 = str2.toUpperCase();
String str5 = str3.toLowerCase();
String str6 = str4.concat(str5);
System.out.println(str6);
}
}
String类的其他功能
替换功能
String replace(char old, char new)
String replace(String old, String new)
去除字符串两端空格
String trim()
按字典顺序比较两个字符串
int compareTo(String str)
int compareToIgnoreCase(String str)
public class StringDemo {
public static void main(String[] args) {
//String 类的其他功能
//替换功能 String replace(char old, char new)
// String replace(String old, String new)
String str = "helloworld";
String str2 = str.replace('l', 's');
System.out.println(str.replace('l', 's'));
System.out.println(str);
System.out.println("------------");
System.out.println(str.replace("owo", "wow"));//
System.out.println("------------");
//去除字符串两端空格
String str3 = " hello world ";
System.out.println(str3+"--");
System.out.println(str3.trim()+"--");
System.out.println("------------");
//按字典比较两个字符串
String str4 = "hello";
String str5 = "hello";
String str6 = "abc";
System.out.println(str4.compareTo(str5));
System.out.println(str4.compareTo(str6));//7 8(h)-1(a)
String str7 = "hel";
System.out.println(str4.compareTo(str7));
}
}
compareTo源码分析
private final char value[];
字符串会自动转换为一个字符数组。
public int compareTo(String anotherString) {
//this -- s1 -- "hello"
//anotherString -- s2 -- "hel"
int len1 = value.length; //this.value.length--s1.toCharArray().length--5
int len2 = anotherString.value.length;//s2.value.length -- s2.toCharArray().length--3
int lim = Math.min(len1, len2); //Math.min(5,3); -- lim=3;
char v1[] = value; //s1.toCharArray()
char v2[] = anotherString.value;
//char v1[] = {'h','e','l','l','o'};
//char v2[] = {'h','e','l'};
int k = 0;
while (k < lim) {
char c1 = v1[k]; //c1='h','e','l'
char c2 = v2[k]; //c2='h','e','l'
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2; //5-3=2;
}
String s1 = "hello";
String s2 = "hel";
System.out.println(s1.compareTo(s2)); // 2
练习:把int数组拼接成字符串
/*练习
* 把数组中的数据按照指定格式拼接成一个字符串
* 举例:int[] arr = {1,2,3}; 输出结果[1, 2, 3]
* */
public class StringTest {
public static void main(String[] args) {
String str = "";
str += "[";
int[] arr = { 1, 2, 3 };
for (int x = 0; x < arr.length; x++) {
if(x == arr.length-1){
str +=arr[x];
str +="]";
}
else{
str +=arr[x];
str +=", ";
}
}
System.out.println(str);
}
}
练习:字符串反转
public class StringDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char[] c = str.toCharArray();
/*char[] d = new char[str.length()];
for (int x = str.length() - 1, y = 0; x >= 0; x--, y++) {
d[y] = c[x];
}
String str2 = String.valueOf(d);
System.out.println(str);
System.out.println(str2);*/
String str2 = "";
for (int x = str.length() - 1; x >= 0; x--) {
str2 += c[x];
}
System.out.println(str2);
}
}
练习:在大串中查找小串
//方法一
public class StringDemo {
public static void main(String[] args) {
String str = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
char[] c = str.toCharArray();
int num = 0;
for (int x = 0; x < c.length; x++) {
if (c[x] == 'j' && c[x + 1] == 'a' && c[x + 2] == 'v' && c[x + 3] == 'a') {
num++;
} else {
continue;
}
}
System.out.println(num);
}
}
//方法二
public class StringDemo {
public static void main(String[] args) {
String str = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
//先查找第一次索引位置
int index = str.indexOf("java");
//定义出现的次数
int num = 0;
while(index != -1){
str = str.substring(index+4);
index = str.indexOf("java");
num++;
}
System.out.println("字符串中共出现了"+num+"次java");
}
}