第七章 –– 常见类之 String 和 StringBuffer和StringBuilder
来源:互联网 发布:手机编程游戏 编辑:程序博客网 时间:2024/06/05 04:17
1. String 类的使用
/*
* 字符串:就是由多个字符组成的一串数据。也可以看成是一个字符数组。
* 通过查看API,我们可以知道
* A:字符串字面值"abc"也可以看成是一个字符串对象。
* B:字符串是常量,一旦被赋值,就不能被改变。
*
* 构造方法:
* 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):把字符串常量值转成字符串
*
* 字符串的方法:
* public int length():返回此字符串的长度。
*/
/*
2. * 字符串的特点:一旦被赋值,就不能改变。
*/
3. 面试题
(1)
/*
* String s = new String(“hello”)和String s = “hello”;的区别?
* 有。前者会创建2个对象,后者创建1个对象。
*
* ==:比较引用类型比较的是地址值是否相同
* equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。
*/
(2)
/*
* 看程序写结果
* 字符串如果是变量相加,先开空间,在拼接。
* 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
*/
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"));
}
}
/*
4. *String类的判断功能:
* boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
* boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
* boolean contains(String str):判断大字符串中是否包含小字符串
* boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
* boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾
* boolean isEmpty():判断字符串是否为空。
*
* 注意:
* 字符串内容为空和字符串对象为空。
* String s = "";
* String s = null;
*/
/*
5. *需求:遍历获取字符串中的每一个字符
*
* 分析:
* A:如何能够拿到每一个字符呢?
* char charAt(int index)
* B:我怎么知道字符到底有多少个呢?
* int length()
*/
/*
6. * String类的获取功能
* int length():获取字符串的长度。
* char charAt(int index):获取指定索引位置的字符
* int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
* 为什么这里是int类型,而不是char类型?
* 原因是:'a'和97其实都可以代表'a'
* int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。
* int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
* int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
* String substring(int start):从指定位置开始截取字符串,默认到末尾。
* String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。
*/
/*
7. *String的转换功能:
* byte[] getBytes():把字符串转换为字节数组。
* char[] toCharArray():把字符串转换为字符数组。
* static String valueOf(char[] chs):把字符数组转成字符串。
* static String valueOf(int i):把int类型的数据转成字符串。
* 注意:String类的valueOf方法可以把任意类型的数据转成字符串。
* String toLowerCase():把字符串转成小写。
* String toUpperCase():把字符串转成大写。
* String concat(String str):把字符串拼接。
*/
/*
8. *String类的其他功能:
*
* 替换功能:
* String replace(char old,char new)
* String replace(String old,String new)
*
* 去除字符串两空格
* String trim()
*
* 按字典顺序比较两个字符串
* int compareTo(String str)
* int compareToIgnoreCase(String str)
*/
/*
9. *如果我们看到问题了,看怎么办呢?
* 看源码。
*/
public class StringTest {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hel";
System.out.println(s1.compareTo(s2)); // 2
}
}
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;
}
面试题
(1)
package cn.itcast_07;
/*
* 需求:把数组中的数据按照指定个格式拼接成一个字符串
* 举例:
* int[] arr = {1,2,3};
* 输出结果:
* "[1, 2, 3]"
* 分析:
* A:定义一个字符串对象,只不过内容为空
* B:先把字符串拼接一个"["
* C:遍历int数组,得到每一个元素
* D:先判断该元素是否为最后一个
* 是:就直接拼接元素和"]"
* 不是:就拼接元素和逗号以及空格
* E:输出拼接后的字符串
*/
public class StringTest {
public static void main(String[] args) {
// 前提是数组已经存在
int[] arr = { 1, 2, 3 };
// 定义一个字符串对象,只不过内容为空
String s = "";
// 先把字符串拼接一个"["
s += "[";
// 遍历int数组,得到每一个元素
for (int x = 0; x < arr.length; x++) {
// 先判断该元素是否为最后一个
if (x == arr.length - 1) {
// 就直接拼接元素和"]"
s += arr[x];
s += "]";
} else {
// 就拼接元素和逗号以及空格
s += arr[x];
s += ", ";
}
}
// 输出拼接后的字符串
System.out.println("最终的字符串是:" + s);
}
}
(2)
package cn.itcast_07;
/*
* 需求:把数组中的数据按照指定个格式拼接成一个字符串
* 举例:
* int[] arr = {1,2,3};
* 输出结果:
* "[1, 2, 3]"
* 分析:
* A:定义一个字符串对象,只不过内容为空
* B:先把字符串拼接一个"["
* C:遍历int数组,得到每一个元素
* D:先判断该元素是否为最后一个
* 是:就直接拼接元素和"]"
* 不是:就拼接元素和逗号以及空格
* E:输出拼接后的字符串
*
* 把代码用功能实现。
*/
public class StringTest2 {
public static void main(String[] args) {
// 前提是数组已经存在
int[] arr = { 1, 2, 3 };
// 写一个功能,实现结果
String result = arrayToString(arr);
System.out.println("最终结果是:" + result);
}
/*
* 两个明确: 返回值类型:String 参数列表:int[] arr
*/
public static String arrayToString(int[] arr) {
// 定义一个字符串
String s = "";
// 先把字符串拼接一个"["
s += "[";
// 遍历int数组,得到每一个元素
for (int x = 0; x < arr.length; x++) {
// 先判断该元素是否为最后一个
if (x == arr.length - 1) {
// 就直接拼接元素和"]"
s += arr[x];
s += "]";
} else {
// 就拼接元素和逗号以及空格
s += arr[x];
s += ", ";
}
}
return s;
}
}
(3)
package cn.itcast_07;
import java.util.Scanner;
/*
* 字符串反转
* 举例:键盘录入”abc”
* 输出结果:”cba”
*
* 分析:
* A:键盘录入一个字符串
* B:定义一个新字符串
* C:倒着遍历字符串,得到每一个字符
* a:length()和charAt()结合
* b:把字符串转成字符数组
* D:用新字符串把每一个字符拼接起来
* E:输出新串
*/
public class StringTest3 {
public static void main(String[] args) {
// 键盘录入一个字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
/*
// 定义一个新字符串
String result = "";
// 把字符串转成字符数组
char[] chs = line.toCharArray();
// 倒着遍历字符串,得到每一个字符
for (int x = chs.length - 1; x >= 0; x--) {
// 用新字符串把每一个字符拼接起来
result += chs[x];
}
// 输出新串
System.out.println("反转后的结果是:" + result);
*/
// 改进为功能实现
String s = myReverse(line);
System.out.println("实现功能后的结果是:" + s);
}
/*
* 两个明确: 返回值类型:String 参数列表:String
*/
public static String myReverse(String s) {
// 定义一个新字符串
String result = "";
// 把字符串转成字符数组
char[] chs = s.toCharArray();
// 倒着遍历字符串,得到每一个字符
for (int x = chs.length - 1; x >= 0; x--) {
// 用新字符串把每一个字符拼接起来
result += chs[x];
}
return result;
}
}
(4)
package cn.itcast_07;
/*
* 统计大串中小串出现的次数
* 举例:
* 在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"
* 结果:
* java出现了5次
*
* 分析:
* 前提:是已经知道了大串和小串。
*
* A:定义一个统计变量,初始化值是0
* B:先在大串中查找一次小串第一次出现的位置
* a:索引是-1,说明不存在了,就返回统计变量
* b:索引不是-1,说明存在,统计变量++
* C:把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把该字符串的值重新赋值给大串
* D:回到B
*/
public class StringTest4 {
public static void main(String[] args) {
// 定义大串
String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
// 定义小串
String minString = "java";
// 写功能实现
int count = getCount(maxString, minString);
System.out.println("Java在大串中出现了:" + count + "次");
}
/*
* 两个明确: 返回值类型:int 参数列表:两个字符串
*/
public static int getCount(String maxString, String minString) {
// 定义一个统计变量,初始化值是0
int count = 0;
// 先在大串中查找一次小串第一次出现的位置
int index = maxString.indexOf(minString);
// 索引不是-1,说明存在,统计变量++
while (index != -1) {
count++;
// 把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把该字符串的值重新赋值给大串
int startIndex = index + minString.length();
maxString = maxString.substring(startIndex);
// 继续查
index = maxString.indexOf(minString);
}
return count;
}
}
(5)
package cn.itcast_07;
/*
* 统计大串中小串出现的次数
* 举例:
* 在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"
* 结果:
* java出现了5次
*
* 分析:
* 前提:是已经知道了大串和小串。
*
* A:定义一个统计变量,初始化值是0
* B:先在大串中查找一次小串第一次出现的位置
* a:索引是-1,说明不存在了,就返回统计变量
* b:索引不是-1,说明存在,统计变量++
* C:把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把该字符串的值重新赋值给大串
* D:回到B
*/
public class StringTest5 {
public static void main(String[] args) {
// 定义大串
String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
// 定义小串
String minString = "java";
// 写功能实现
int count = getCount(maxString, minString);
System.out.println("Java在大串中出现了:" + count + "次");
}
/*
* 两个明确: 返回值类型:int 参数列表:两个字符串
*/
public static int getCount(String maxString, String minString) {
// 定义一个统计变量,初始化值是0
int count = 0;
/*
// 先在大串中查找一次小串第一次出现的位置
int index = maxString.indexOf(minString);
// 索引不是-1,说明存在,统计变量++
while (index != -1) {
count++;
// 把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把该字符串的值重新赋值给大串
// int startIndex = index + minString.length();
// maxString = maxString.substring(startIndex);
maxString = maxString.substring(index + minString.length());
// 继续查
index = maxString.indexOf(minString);
}
*/
int index;
//先查,赋值,判断
while((index=maxString.indexOf(minString))!=-1){
count++;
maxString = maxString.substring(index + minString.length());
}
return count;
}
}
总结
1:Scanner的使用(了解)
(1)在JDK5以后出现的用于键盘录入数据的类。
(2)构造方法:
A:讲解了System.in这个东西。
它其实是标准的输入流,对应于键盘录入
B:构造方法
InputStream is = System.in;
Scanner(InputStream is)
C:常用的格式
Scanner sc = new Scanner(System.in);
(3)基本方法格式:
A:hasNextXxx() 判断是否是某种类型的
B:nextXxx() 返回某种类型的元素
(4)要掌握的两个方法
A:public int nextInt()
B:public String nextLine()
(5)需要注意的小问题
A:同一个Scanner对象,先获取数值,再获取字符串会出现一个小问题。
B:解决方案:
a:重新定义一个Scanner对象
b:把所有的数据都用字符串获取,然后再进行相应的转换
2:String类的概述和使用(掌握)
(1)多个字符组成的一串数据。
其实它可以和字符数组进行相互转换。
(2)构造方法:
A:public String()
B:public String(byte[] bytes)
C:public String(byte[] bytes,int offset,int length)
D:public String(char[] value)
E:public String(char[] value,int offset,int count)
F:public String(String original)
下面的这一个虽然不是构造方法,但是结果也是一个字符串对象
G:String s = "hello";
(3)字符串的特点
A:字符串一旦被赋值,就不能改变。
注意:这里指的是字符串的内容不能改变,而不是引用不能改变。
B:字面值作为字符串对象和通过构造方法创建对象的不同
String s = new String("hello");和String s = "hello"的区别?
(4)字符串的面试题(看程序写结果)
A:==和equals()
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
B:字符串的拼接
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
(5)字符串的功能(自己补齐方法中文意思)
A:判断功能
boolean equals(Object obj)
boolean equalsIgnoreCase(String str)
boolean contains(String str)
boolean startsWith(String str)
boolean endsWith(String str)
boolean isEmpty()
B:获取功能
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)
String substring(int start)
String substring(int start,int end)
C:转换功能
byte[] getBytes()
char[] toCharArray()
static String valueOf(char[] chs)
static String valueOf(int i)
String toLowerCase()
String toUpperCase()
String concat(String str)
D:其他功能
a:替换功能
String replace(char old,char new)
String replace(String old,String new)
b:去空格功能
String trim()
c:按字典比较功能
int compareTo(String str)
int compareToIgnoreCase(String str)
(6)字符串的案例
A:模拟用户登录
B:字符串遍历
C:统计字符串中大写,小写及数字字符的个数
D:把字符串的首字母转成大写,其他小写
E:把int数组拼接成一个指定格式的字符串
F:字符串反转
G:统计大串中小串出现的次数
3:StringBuffer(掌握)
(1)用字符串做拼接,比较耗时并且也耗内存,而这种拼接操作又是比较常见的,为了解决这个问题,Java就提供了
一个字符串缓冲区类。StringBuffer供我们使用。
(2)StringBuffer的构造方法
A:StringBuffer()
B:StringBuffer(int size)
C:StringBuffer(String str)
(3)StringBuffer的常见功能(自己补齐方法的声明和方法的解释)
A:添加功能
append()
insert()
B:删除功能
deleteCharAt()
delete()
C:替换功能
replace()
D:反转功能
reverse()
E:截取功能(注意这个返回值)
substring()
(4)StringBuffer的练习(做一遍)
A:String和StringBuffer相互转换
String -- StringBuffer
构造方法
StringBuffer -- String
toString()方法
B:字符串的拼接
C:把字符串反转
D:判断一个字符串是否对称
(5)面试题
小细节:
StringBuffer:同步的,数据安全,效率低。
StringBuilder:不同步的,数据不安全,效率高。
A:String,StringBuffer,StringBuilder的区别
B:StringBuffer和数组的区别?
(6)注意的问题:
String作为形式参数,StringBuffer作为形式参数。
3:数组高级以及Arrays(掌握)
(1)排序
A:冒泡排序
相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处。同理,其他的元素就可以排好。
public static void bubbleSort(int[] arr) {
for(int x=0; x<arr.length-1; x++) {
for(int y=0; y<arr.length-1-x; y++) {
if(arr[y] > arr[y+1]) {
int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1] = temp;
}
}
}
}
B:选择排序
把0索引的元素,和索引1以后的元素都进行比较,第一次完毕,最小值出现在了0索引。同理,其他的元素就可以排好。
public static void selectSort(int[] arr) {
for(int x=0; x<arr.length-1; x++) {
for(int y=x+1; y<arr.length; y++) {
if(arr[y] < arr[x]) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
}
(2)查找
A:基本查找
针对数组无序的情况
public static int getIndex(int[] arr,int value) {
int index = -1;
for(int x=0; x<arr.length; x++) {
if(arr[x] == value) {
index = x;
break;
}
}
return index;
}
B:二分查找(折半查找)
针对数组有序的情况(千万不要先排序,在查找)
public static int binarySearch(int[] arr,int value) {
int min = 0;
int max = arr.length-1;
int mid = (min+max)/2;
while(arr[mid] != value) {
if(arr[mid] > value) {
max = mid - 1;
}else if(arr[mid] < value) {
min = mid + 1;
}
if(min > max) {
return -1;
}
mid = (min+max)/2;
}
return mid;
}
(3)Arrays工具类
A:是针对数组进行操作的工具类。包括排序和查找等功能。
B:要掌握的方法(自己补齐方法)
把数组转成字符串:toString()
排序:sort()
二分查找:binarySearch()
(4)Arrays工具类的源码解析
(5)把字符串中的字符进行排序
举例:
"edacbgf"
得到结果
"abcdefg"
3:Integer(掌握)
(1)为了让基本类型的数据进行更多的操作,Java就为每种基本类型提供了对应的包装类类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
(2)Integer的构造方法
A:Integer i = new Integer(100);
B:Integer i = new Integer("100");
注意:这里的字符串必须是由数字字符组成
(3)String和int的相互转换
A:String -- int
Integer.parseInt("100");
B:int -- String
String.valueOf(100);
(4)其他的功能(了解)
进制转换
(5)JDK5的新特性
自动装箱 基本类型--引用类型
自动拆箱 引用类型--基本类型
把下面的这个代码理解即可:
Integer i = 100;
i += 200;
(6)面试题
-128到127之间的数据缓冲池问题
4:Character(了解)
(1)Character构造方法
Character ch = new Character('a');
(2)要掌握的方法:(自己补齐)
A:判断给定的字符是否是大写 isUpperCase()
B:判断给定的字符是否是小写 isLowerCase()
C:判断给定的字符是否是数字字符 isDigit()
D:把给定的字符转成大写 toUpperCase
E:把给定的字符转成小写 toLowerCase
(3)案例:
统计字符串中大写,小写及数字字符出现的次数
package cn.itcast_01;
/*
* 线程安全(多线程讲解)
* 安全 -- 同步 -- 数据是安全的
* 不安全 -- 不同步 -- 效率高一些
* 安全和效率问题是永远困扰我们的问题。
* 安全:医院的网站,银行网站
* 效率:新闻网站,论坛之类的
*
* StringBuffer:
* 线程安全的可变字符串。
*
* StringBuffer和String的区别?
* 前者长度和内容可变,后者不可变。
* 如果使用前者做字符串的拼接,不会浪费太多的资源。
*
* StringBuffer的构造方法:
* public StringBuffer():无参构造方法
* public StringBuffer(int capacity):指定容量的字符串缓冲区对象
* public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
*
* StringBuffer的方法:
* public int capacity():返回当前容量。 理论值
* public int length():返回长度(字符数)。 实际值
*/
public class StringBufferDemo {
public static void main(String[] args) {
// public StringBuffer():无参构造方法
StringBuffer sb = new StringBuffer();
System.out.println("sb:" + sb);
System.out.println("sb.capacity():" + sb.capacity());
System.out.println("sb.length():" + sb.length());
System.out.println("--------------------------");
// public StringBuffer(int capacity):指定容量的字符串缓冲区对象
StringBuffer sb2 = new StringBuffer(50);
System.out.println("sb2:" + sb2);
System.out.println("sb2.capacity():" + sb2.capacity());
System.out.println("sb2.length():" + sb2.length());
System.out.println("--------------------------");
// public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
StringBuffer sb3 = new StringBuffer("hello");
System.out.println("sb3:" + sb3);
System.out.println("sb3.capacity():" + sb3.capacity());
System.out.println("sb3.length():" + sb3.length());
}
}
package cn.itcast_02;
/*
* StringBuffer的添加功能:
* public StringBuffer append(String str):可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
*
* public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
*/
public class StringBufferDemo {
public static void main(String[] args) {
// 创建字符串缓冲区对象
StringBuffer sb = new StringBuffer();
// public StringBuffer append(String str)
// StringBuffer sb2 = sb.append("hello");
// System.out.println("sb:" + sb);
// System.out.println("sb2:" + sb2);
// System.out.println(sb == sb2); // true
// 一步一步的添加数据
// sb.append("hello");
// sb.append(true);
// sb.append(12);
// sb.append(34.56);
// 链式编程
sb.append("hello").append(true).append(12).append(34.56);
System.out.println("sb:" + sb);
// public StringBuffer insert(int offset,String
// str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
sb.insert(5, "world");
System.out.println("sb:" + sb);
}
}
package cn.itcast_03;
/*
* StringBuffer的删除功能
* public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
* public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
*/
public class StringBufferDemo {
public static void main(String[] args) {
// 创建对象
StringBuffer sb = new StringBuffer();
// 添加功能
sb.append("hello").append("world").append("java");
System.out.println("sb:" + sb);
// public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
// 需求:我要删除e这个字符,肿么办?
// sb.deleteCharAt(1);
// 需求:我要删除第一个l这个字符,肿么办?
// sb.deleteCharAt(1);
// public StringBuffer delete(int start,int
// end):删除从指定位置开始指定位置结束的内容,并返回本身
// 需求:我要删除world这个字符串,肿么办?
// sb.delete(5, 10);
// 需求:我要删除所有的数据
sb.delete(0, sb.length());
System.out.println("sb:" + sb);
}
}
package cn.itcast_04;
/*
* StringBuffer的替换功能:
* public StringBuffer replace(int start,int end,String str):从start开始到end用str替换
*/
public class StringBufferDemo {
public static void main(String[] args) {
// 创建字符串缓冲区对象
StringBuffer sb = new StringBuffer();
// 添加数据
sb.append("hello");
sb.append("world");
sb.append("java");
System.out.println("sb:" + sb);
// public StringBuffer replace(int start,int end,String
// str):从start开始到end用str替换
// 需求:我要把world这个数据替换为"节日快乐"
sb.replace(5, 10, "节日快乐");
System.out.println("sb:" + sb);
}
}
package cn.itcast_05;
/*
* StringBuffer的反转功能:
* public StringBuffer reverse()
*/
public class StringBufferDemo {
public static void main(String[] args) {
// 创建字符串缓冲区对象
StringBuffer sb = new StringBuffer();
// 添加数据
sb.append("霞青林爱我");
System.out.println("sb:" + sb);
// public StringBuffer reverse()
sb.reverse();
System.out.println("sb:" + sb);
}
}
package cn.itcast_06;
/*
* StringBuffer的截取功能:注意返回值类型不再是StringBuffer本身了
* public String substring(int start)
* public String substring(int start,int end)
*/
public class StringBufferDemo {
public static void main(String[] args) {
// 创建字符串缓冲区对象
StringBuffer sb = new StringBuffer();
// 添加元素
sb.append("hello").append("world").append("java");
System.out.println("sb:" + sb);
// 截取功能
// public String substring(int start)
String s = sb.substring(5);
System.out.println("s:" + s);
System.out.println("sb:" + sb);
// public String substring(int start,int end)
String ss = sb.substring(5, 10);
System.out.println("ss:" + ss);
System.out.println("sb:" + sb);
}
}
package cn.itcast_07;
/*
* 为什么我们要讲解类之间的转换:
* A -- B的转换
* 我们把A转换为B,其实是为了使用B的功能。
* B -- A的转换
* 我们可能要的结果是A类型,所以还得转回来。
*
* String和StringBuffer的相互转换?
*/
public class StringBufferTest {
public static void main(String[] args) {
// String -- StringBuffer
String s = "hello";
// 注意:不能把字符串的值直接赋值给StringBuffer
// StringBuffer sb = "hello";
// StringBuffer sb = s;
// 方式1:通过构造方法
StringBuffer sb = new StringBuffer(s);
// 方式2:通过append()方法
StringBuffer sb2 = new StringBuffer();
sb2.append(s);
System.out.println("sb:" + sb);
System.out.println("sb2:" + sb2);
System.out.println("---------------");
// StringBuffer -- String
StringBuffer buffer = new StringBuffer("java");
// String(StringBuffer buffer)
// 方式1:通过构造方法
String str = new String(buffer);
// 方式2:通过toString()方法
String str2 = buffer.toString();
System.out.println("str:" + str);
System.out.println("str2:" + str2);
}
}
package cn.itcast_07;
/*
* 把数组拼接成一个字符串
*/
public class StringBufferTest2 {
public static void main(String[] args) {
// 定义一个数组
int[] arr = { 44, 33, 55, 11, 22 };
// 定义功能
// 方式1:用String做拼接的方式
String s1 = arrayToString(arr);
System.out.println("s1:" + s1);
// 方式2:用StringBuffer做拼接的方式
String s2 = arrayToString2(arr);
System.out.println("s2:" + s2);
}
// 用StringBuffer做拼接的方式
public static String arrayToString2(int[] arr) {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
sb.append(arr[x]);
} else {
sb.append(arr[x]).append(", ");
}
}
sb.append("]");
return sb.toString();
}
// 用String做拼接的方式
public static String arrayToString(int[] arr) {
String s = "";
s += "[";
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
s += arr[x];
} else {
s += arr[x];
s += ", ";
}
}
s += "]";
return s;
}
}
package cn.itcast_07;
import java.util.Scanner;
/*
* 把字符串反转
*/
public class StringBufferTest3 {
public static void main(String[] args) {
// 键盘录入数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入数据:");
String s = sc.nextLine();
// 方式1:用String做拼接
String s1 = myReverse(s);
System.out.println("s1:" + s1);
// 方式2:用StringBuffer的reverse()功能
String s2 = myReverse2(s);
System.out.println("s2:" + s2);
}
// 用StringBuffer的reverse()功能
public static String myReverse2(String s) {
// StringBuffer sb = new StringBuffer();
// sb.append(s);
// StringBuffer sb = new StringBuffer(s);
// sb.reverse();
// return sb.toString();
// 简易版
return new StringBuffer(s).reverse().toString();
}
// 用String做拼接
public static String myReverse(String s) {
String result = "";
char[] chs = s.toCharArray();
for (int x = chs.length - 1; x >= 0; x--) {
// char ch = chs[x];
// result += ch;
result += chs[x];
}
return result;
}
}
package cn.itcast_07;
import java.util.Scanner;
/*
* 判断一个字符串是否是对称字符串
* 例如"abc"不是对称字符串,"aba"、"abba"、"aaa"、"mnanm"是对称字符串
*
* 分析:
* 判断一个字符串是否是对称的字符串,我只需要把
* 第一个和最后一个比较
* 第二个和倒数第二个比较
* ...
* 比较的次数是长度除以2。
*/
public class StringBufferTest4 {
public static void main(String[] args) {
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String s = sc.nextLine();
// 一个一个的比较
boolean b = isSame(s);
System.out.println("b:" + b);
//用字符串缓冲区的反转功能
boolean b2 = isSame2(s);
System.out.println("b2:"+b2);
}
public static boolean isSame2(String s) {
return new StringBuffer(s).reverse().toString().equals(s);
}
// public static boolean isSame(String s) {
// // 把字符串转成字符数组
// char[] chs = s.toCharArray();
//
// for (int start = 0, end = chs.length - 1; start <= end; start++, end--) {
// if (chs[start] != chs[end]) {
// return false;
// }
// }
//
// return true;
// }
public static boolean isSame(String s) {
boolean flag = true;
// 把字符串转成字符数组
char[] chs = s.toCharArray();
for (int start = 0, end = chs.length - 1; start <= end; start++, end--) {
if (chs[start] != chs[end]) {
flag = false;
break;
}
}
return flag;
}
}
package cn.itcast_08;
/*
* 面试题:
* 1:String,StringBuffer,StringBuilder的区别?
* A:String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。
* B:StringBuffer是同步的,数据安全,效率低;StringBuilder是不同步的,数据不安全,效率高
*
* 2:StringBuffer和数组的区别?
* 二者都可以看出是一个容器,装其他的数据。
* 但是呢,StringBuffer的数据最终是一个字符串数据。
* 而数组可以放置多种数据,但必须是同一种数据类型的。
*
* 3:形式参数问题
* String作为参数传递
* StringBuffer作为参数传递
*
* 形式参数:
* 基本类型:形式参数的改变不影响实际参数
* 引用类型:形式参数的改变直接影响实际参数
*
* 注意:
* String作为参数传递,效果和基本类型作为参数传递是一样的。
*/
public class StringBufferDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
System.out.println(s1 + "---" + s2);// hello---world
change(s1, s2);
System.out.println(s1 + "---" + s2);// hello---world
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("world");
System.out.println(sb1 + "---" + sb2);// hello---world
change(sb1, sb2);
System.out.println(sb1 + "---" + sb2);// hello---worldworld
}
public static void change(StringBuffer sb1, StringBuffer sb2) {
sb1 = sb2;
sb2.append(sb1);
}
public static void change(String s1, String s2) {
s1 = s2;
s2 = s1 + s2;
}
}
- 第七章 –– 常见类之 String 和 StringBuffer和StringBuilder
- String、StringBuffer和StringBuilder类
- String、StringBuffer和StringBuilder类
- String、StringBuffer和StringBuilder类
- String 、StringBuffer 和 StringBuilder
- String、StringBuffer和StringBuilder
- String、StringBuffer和StringBuilder
- String、StringBuffer和StringBuilder
- String、StringBuffer和StringBuilder
- String Stringbuffer和StringBuilder
- String ,StringBuffer和StringBuilder
- String、StringBuffer和StringBuilder
- String、StringBuffer和StringBuilder
- String StringBuffer和StringBuilder
- String、StringBuffer和StringBuilder
- String和StringBuffer,StringBuilder
- String、StringBuffer和StringBuilder
- String, StringBuffer和 StringBuilder
- 欢迎使用CSDN-markdown编辑器
- SQL注入和xss初步尝试
- JavaScript/JQuery获取地址栏url参数的方法
- Linux下配置oracle12c创建pdb过程
- 用户,用户组,角色和权限
- 第七章 –– 常见类之 String 和 StringBuffer和StringBuilder
- AF:Request failed: unacceptable content-type: text/html"
- Sring+ibatis+easyui简单配置,包括事务以及缓存配置等
- 【问底】徐汉彬:Web系统大规模并发——电商秒杀与抢购
- 六、matplotlib系列---pyplot基础图表函数概述
- UVALive 4683 Find The Number(容斥+二分)
- Java并发编程(三)Volatile
- 宽度一定且使背景图片不变形的情况下,背景图片不随内容滚动(固定)
- Eclipse(Java EE) 报错:Server Tomcat v7.0 Server at localhost failed to start.