(五)黑马程序员——Java中的字符串操作类(String、StringBuilder、StringBuffer)

来源:互联网 发布:我的世界天堂js怎么用 编辑:程序博客网 时间:2024/06/01 07:56
------- <a href="http://www.itheima.com" target="blank">android培训</a>、
<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

java语言的字符串序列是通过字符串类实现的。java提供了3个字符串类:String类、StringBuilder类和StringBuffer类。String类是不变字符串,StringBuffer类和StringBuilder类是可变字符串,这3种字符串都是16位的Unicode字符序列,并且这3个类都被声明为final类,因此不能被继承。

一、String

常见构造方法
* public String():空构造
* public String(byte[] bytes):把字节数组转成字符串
* public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串
* public String(char[] value):把字符数组转成字符串
* public String(char[] value,int index,int count):把字符数组的一部分转成字符串
* public String(String original):把字符串常量值转成字符串

判断功能
* boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
* boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
* boolean contains(String str):判断大字符串中是否包含小字符串
* boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
* boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾
* boolean isEmpty():判断字符串是否为空。
案例:
package com.heima.string;
 
public class Demo4_StringMethod {
public static void main(String[] args) {
//demo1();
//demo2();
String s1 = "heima";
String s2 = "";
String s3 = null;
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
System.out.println(s3.isEmpty());//java.lang.NullPointerException
}
 
private static void demo2() {
String s1 = "我爱heima,哈哈";
String s2 = "heima";
String s3 = "baima";
String s4 = "我爱";
String s5 = "哈哈";
System.out.println(s1.contains(s2));//判断是否包含传入的字符串
System.out.println(s1.contains(s3));
System.out.println("------------------");
System.out.println(s1.startsWith(s4));//判断是否以传入的字符串开头
System.out.println(s1.startsWith(s5));
System.out.println("------------------");
System.out.println(s1.endsWith(s4));//判断是否以传入的字符串结尾
System.out.println(s1.endsWith(s5));
}
 
private static void demo1() {
String s1 = "heima";
String s2 = "heima";
String s3 = "HeiMa";
System.out.println(s1.equals(s2));//true
System.out.println(s2.equals(s3));//false
System.out.println("---------------");
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3)); //不区分大小写
}
 
}

 
模拟用户登录
* 案例演示
* 需求:模拟登录,给三次机会,并提示还有几次。
* 用户名和密码都是admin
/**
* * A:案例演示
* 需求:模拟登录,给三次机会,并提示还有几次。
* 用户名和密码都是admin
* @author JX
*
*/
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 3;
while(true) {
System.out.println("请输入用户名:");
String userName = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
if("admin".equals(userName)&&"admin".equals(password)) {
System.out.println("欢迎光临:"+userName);
break;
} else {
if(--count==0) {
System.out.println("登录次数已到,请明天再来吧!");
break;
} else{
System.out.println("您还有"+(count)+"机会!");
}
}
}
}
}

String类的获取功能
* int length():获取字符串的长度。
* char charAt(int index):获取指定索引位置的字符
* int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
* int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。
* int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
* int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
* lastIndexOf
* String substring(int start):从指定位置开始截取字符串,默认到末尾。
* String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。
案例:
package com.itheima.string;
 
public class Demo5_StringMethod {
public static void main(String[] args) {
//demo1();
//demo2();
//demo3();
//demo4();
String s = "woaiheima";
s.substring(4);//subString会产生一个新额字符串,需要将新的字符串记录
System.out.println(s);
}
 
private static void demo4() {
String s1 = "heimawudi";
String s2 = s1.substring(5);
System.out.println(s2);
String s3 = s1.substring(0, 5);//包含头,不包含尾,左闭右开
System.out.println(s3);
}
 
private static void demo3() {
String s1 = "woaiheima";
int index1 = s1.indexOf('a', 3);//从指定位置开始向后找
System.out.println(index1);
int index2 = s1.lastIndexOf('a');//从后向前找,第一次出现的字符
System.out.println(index2);
int index3 = s1.lastIndexOf('a', 7);//从指定位置向前找
System.out.println(index3);
}
 
private static void demo2() {
String s1 = "heima";
int index = s1.indexOf('e');            //参数接收的是int类型的,传递char类型的会自动提升
System.out.println(index);
int index2 = s1.indexOf('z');//如果不存在返回就是-1
System.out.println(index2);
int index3 = s1.indexOf("ma");//获取字符串中第一个字符出现的位置
System.out.println(index3);
int index4 = s1.indexOf("ia");
System.out.println(index4);
}
 
private static void demo1() {
//int[] arr = {11,22,33};
//System.out.println(arr.length);//数组中的length是属性
String s1 = "heima";
System.out.println(s1.length());//length()是一个方法,获取的是每一个字符的个数
String s2 = "你要减肥,造吗?";
System.out.println(s2.length());
char c = s2.charAt(5);//根据索引获取对应位置的字符
System.out.println(c);
char c2 = s2.charAt(10);//StringIndexOutOfBoundsException字符串索引越界异常
System.out.println(c2);
}
 
}

String的转换功能:
* byte[] getBytes():把字符串转换为字节数组。   // 字符串  ---.>字节数组
* char[] toCharArray():把字符串转换为字符数组。//字符串 --->字符数组
* static String valueOf(char[] chs):把字符数组转成字符串。//字符数组---->字符串
* static String valueOf(int i):把int类型的数据转成字符串。 // valueOf可以把任意类型--->字符串
* 注意:String类的valueOf方法可以把任意类型的数据转成字符串。

* String toLowerCase():把字符串转成小写。(了解)
* String toUpperCase():把字符串转成大写。
* String concat(String str):把字符串拼接。
案例:
package com.itheima.string;
 
import com.itheima.bean.Person;
 
public class Demo6_StringMethod {
public static void main(String[] args) {
//demo1();
//demo2();
//demo3();
String s1 = "heiMA";
String s2 = "chengxuYUAN";
String s3 = s1.toLowerCase();
String s4 = s2.toUpperCase();
System.out.println(s3);
System.out.println(s4);
System.out.println(s3 + s4);//用+拼接字符串更强大,可以用字符串与任意类型相加
System.out.println(s3.concat(s4));//concat方法调用的和传入的都必须是字符串
}
 
private static void demo3() {
char[] arr = {'a','b','c'};
//底String s = String.valueOf(arr);层是由String类的构造方法完成的
System.out.println(s);
String s2 = String.valueOf(100);//将100转换为字符串
System.out.println(s2 + 100);
Person p1 = new Person("张三", 23);
System.out.println(p1);
String s3 = String.valueOf(p1);//调用的是对象的toString方法
System.out.println(s3);
}
 
private static void demo2() {
String s = "heima";
char[] arr = s.toCharArray();//将字符串转换为字符数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
 
private static void demo1() {
String s1 = "abc";
byte[] arr = s1.getBytes();
for (int i = 0; i < arr.length; i++) {
//System.out.print(arr[i] + " ");
}
String s2 = "你好你好";
byte[] arr2 = s2.getBytes();//通过gbk码表将字符串转换成字节数组
for (int i = 0; i < arr2.length; i++) {//编码:把我们看的懂转换为计算机看的懂得
//System.out.print(arr2[i] + " ");//gbk码表一个中文代表两个字节
}//gbk码表特点,中文的第一个字节肯定是负数
String s3 = "琲";
byte[] arr3 = s3.getBytes();
for (int i = 0; i < arr3.length; i++) {
System.out.print(arr3[i] + " ");
}
}
 
}
Person类的内容:
package com.itheima.bean;
 
public class Person {
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}

String类的其他功能
* A:String的替换功能
* String replace(char old,char new)
* String replace(String old,String new)
* B:String的去除字符串两空格
* String trim()
* C:String的按字典顺序比较两个字符串
* int com
pareTo(String str)
* int compareToIgnoreCase(String str)
案例:
package com.itheima.string;
 
public class Demo7_StringMethod {
 
public static void main(String[] args) {
//demo1();
//demo2();
demo3();
/*
* public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);//将c1字符转换成大写
c2 = Character.toUpperCase(c2);//将c2字符转换成大写
if (c1 != c2) {
c1 = Character.toLowerCase(c1);//将c1字符转换成小写
c2 = Character.toLowerCase(c2);//将c2字符转换成小写
if (c1 != c2) {
// No overflow because of numeric promotion
return c1 - c2;
}
}
}
}
return n1 - n2;
*/
}
 
private static void demo3() {
String s1 = "a";
String s2 = "aaaa";
int num = s1.compareTo(s2);//按照码表值比较
System.out.println(num);
String s3 = "黑";
String s4 = "马";
int num2 = s3.compareTo(s4);
System.out.println('黑' + 0);//查找的是unicode码表值
System.out.println('马' + 0);
System.out.println(num2);
String s5 = "heima";
String s6 = "HEIMA";
int num3 = s5.compareTo(s6);
System.out.println(num3);
int num4 = s5.compareToIgnoreCase(s6);
System.out.println(num4);
}
 
private static void demo2() {
String s = " hei ma ";
String s2 = s.trim();
System.out.println(s2);
}
 
private static void demo1() {
String s = "heima";
String s2 = s.replace('i', 'o');//用o替换i
System.out.println(s2);
String s3 = s.replace('z', 'o');//z不存在,保留原字符不改变
System.out.println(s3);
String s4 = s.replace("ei", "ao");
System.out.println(s4);
}
 
}

案例演示: 在大串中查找小串出现的次数
* 统计大串中小串出现的次数
  1. package com.itheima.test;
  2. public class Test7 {
  3. public static void main(String[] args) {
  4. //定义大串
  5. String max = "woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma";
  6. //定义小串
  7. String min = "heima";
  8. //定义计数器变量
  9. int count = 0;
  10. //定义索引
  11. int index = 0;
  12. //定义循环,判断小串是否在大串中出现
  13. while((index = max.indexOf(min)) != -1) {
  14. count++;//计数器自增
  15. max = max.substring(index + min.length());
  16. }
  17. System.out.println(count);
  18. }
  19. }


二、StringBuffer

StringBuffer类概述
* 线程安全的可变字符序列 

StringBuffer和String的区别
* String是一个不可变的字符序列
* StringBuffer是一个可变的字符序列 

StringBuffer的构造方法:
* public StringBuffer():无参构造方法
* public StringBuffer(int capacity):指定容量的字符串缓冲区对象
* public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
* StringBuffer的方法:
* public int capacity():返回当前容量。理论值(不掌握)
* public int length():返回长度(字符数)。 实际值
* 案例:
* 构造方法和长度方法的使用
package com.heima.stringbuffer;
 
public class Demo1_StringBuffer {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
System.out.println(sb.length());//容器中的字符个数,实际值
System.out.println(sb.capacity());//容器的初始容量,理论值
StringBuffer sb2 = new StringBuffer(10);
System.out.println(sb2.length());
System.out.println(sb2.capacity());
StringBuffer sb3 = new StringBuffer("heima");
System.out.println(sb3.length());//实际字符的个数
System.out.println(sb3.capacity());//字符串的length + 初始容量
}
 
}

StringBuffer的添加功能
* public StringBuffer append(String str):
* 可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
* public StringBuffer insert(int offset,String str):
* 在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
案例:
package com.heima.stringbuffer;
 
public class Demo2_StringBuffer {
 
/**
* StringBuffer是字符串缓冲区,当new的时候是在堆内存创建了一个对象,底层是一个长度为16的字符数组
当调用添加的方法时,不会再重新创建对象,在不断向原缓冲区添加字符
*/
public static void main(String[] args) {
//demo1();
demo2();
}
 
private static void demo2() {
StringBuffer sb = new StringBuffer("1234");
sb.insert(3, "heima");//在指定位置添加元素,如果没有指定位置的索引就会报索引越界异常
System.out.println(sb);
}
 
private static void demo1() {
StringBuffer sb = new StringBuffer();
StringBuffer sb2 = sb.append(true);
StringBuffer sb3 = sb.append("heima");
StringBuffer sb4 = sb.append(100);
System.out.println(sb.toString());//StringBuffer类中重写了toString方法,显示的是对象中的属性值
System.out.println(sb2.toString());
System.out.println(sb3.toString());
System.out.println(sb4.toString());
}
 
}

StringBuffer的删除功能)
* A:StringBuffer的删除功能
* public StringBuffer deleteCharAt(int index):
* 删除指定位置的字符,并返回本身
* public StringBuffer delete(int start,int end):
* 删除从指定位置开始指定位置结束的内容,并返回本身
案例:
package com.heima.stringbuffer;
 
public class Demo3_StringBuffer {
 
/**
* * A:StringBuffer的删除功能
* public StringBuffer deleteCharAt(int index):
* 删除指定位置的字符,并返回本身
* public StringBuffer delete(int start,int end):
* 删除从指定位置开始指定位置结束的内容,并返回本身
*/
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
//sb.deleteCharAt(5);//当缓冲区中这个索引上没有元素的时候就会报StringIndexOutOfBoundsException
sb.append("heima");
//sb.deleteCharAt(4);//根据索引删除掉索引位置上对应的字符
//sb.delete(0, 2);//删除的时候是包含头,不包含尾
//System.out.println(sb);
//sb.delete(0, sb.length());//清空缓冲区,因为包含头不包含尾,最大索引为length-1
//System.out.println(sb);
sb = new StringBuffer();//不要用这种方式清空缓冲区,原来的会变成垃圾,浪费内存
System.out.println(sb);
}
 
}

###12.05_常见对象(StringBuffer的替换和反转功能)
* A:StringBuffer的替换功能
* public StringBuffer replace(int start,int end,String str):
* 从start开始到end用str替换
* B:StringBuffer的反转功能
* public StringBuffer reverse():
* 字符串反转
案例:
package com.heima.stringbuffer;
 
public class Demo4_StringBufferMethod {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("heima");
//sb.replace(0, 3, "bai");//替换
//System.out.println(sb);
StringBuffer sb = new StringBuffer("我爱总复习");
sb.reverse();
System.out.println(sb);
}
 
}


###12.06_常见对象(StringBuffer的截取功能及注意事项)
* A:StringBuffer的截取功能
* public String substring(int start):
* 从指定位置截取到末尾
* public String substring(int start,int end):
* 截取从指定位置开始到结束位置,包括开始位置,不包括结束位置
* B:注意事项
* 注意:返回值类型不再是StringBuffer本身
案例:
package com.heima.stringbuffer;
 
public class Demo5_StringBufferMethod {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("woaiheima");
//String str = sb.substring(4);
//System.out.println(str);
//System.out.println(sb);
String str3 = sb.substring(4, 7);
System.out.println(str3);
}
 
}

StringBuffer和String的相互转换
* String -- StringBuffer
* a:通过构造方法
* b:通过append()方法
* StringBuffer -- String
* a:通过构造方法
* b:通过toString()方法
* c:通过subString(0,length);
案例:
package com.heima.stringbuffer;
 
public class Demo6_StringBuffer {
public static void main(String[] args) {
//demo1();
StringBuffer sb = new StringBuffer("heima");
String s1 = new String(sb);                //通过构造将StringBuffer转换为String
System.out.println(s1);
String s2 = sb.toString();              //通过toString方法将StringBuffer转换为String
System.out.println(s2);
String s3 = sb.substring(0, sb.length());    //通过截取子字符串将StringBuffer转换为String
System.out.println(s3);
}
 
private static void demo1() {
StringBuffer sb1 = new StringBuffer("heima");//通过构造方法将字符串转换为StringBuffer对象
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer();
sb2.append("heima");//通过append方法将字符串转换为StringBuffer对象
System.out.println(sb2);
}
 
}


三、StringBuilder

StringBuilder类概述
* 线程不安全的可变字符序列 

StringBuffer和StringBuilder的区别
* StringBuffer是jdk1.0版本的,是线程安全的,效率低
* StringBuilder是jdk1.5版本的,是线程不安全的,效率高

String和StringBuffer,StringBuilder的区别
* String是一个不可变的字符序列
* StringBuffer,StringBuilder是可变的字符序列

功能演示:
与StringBuffer类似

0 0