String类
1概述
java.lang.String 类代表字符串。Java程序中所有的字符串⽂字(例如 “abc” )都可以被看作
是实现此类的实例。
类 String 中包括⽤于检查各个字符串的⽅法,⽐如⽤于⽐较字符串,搜索字符串,提取⼦字符
串以及创建具有翻译为⼤写或⼩写的所有字符的字符串的副本。
特点
- 字符串不变:字符串的值在创建后不能被更改。
String s1 = “abc”;
s1 += “d”;
System.out.println(s1); // “abcd” //
内存中有"abc",“abcd"两个对象,s1从指向"abc”,改变指向,指向了"abcd"
- 因为String对象是不可变的,所以它们可以被共享。
String s1 = “abc”;
String s2 = “abc”;
// 内存中只有⼀个"abc"对象被创建,同时被s1和s2共享 s1,s2同时指向 "abc’
- “abc” 等效于 char[] data = {‘a’ , ‘b’ , ‘c’}
例如: String str = “abc”;
相当于: char data[] = {‘a’, ‘b’, ‘c’};
String str= new String(data);
// String底层是靠字符数组实现的。
4.String 重写了toString(),equals(),hashcode();
2 使⽤步骤
查看类
java.lang.String :此类不需要导⼊。
查看构造⽅法
public String() :初始化新创建的String对象,以使其表示空字符序列。
public String(char[] value) :通过当前参数中的字符数组来构造新的String。
public String(byte[] bytes) :通过使⽤平台的默认字符集解码当前参数中的字节
数组来构造新的String。 构造举例,
// ⽆参构造
String str = new String();
// 通过字符数组构造
char chars[] = {'a', 'b', 'c'};
String str2 = new String(chars);
// 通过字节数组构造
byte bytes[] = {97, 98, 99};
String str3 = new String(bytes);
3 常⽤⽅法
3.1判断功能的⽅法
public boolean equals(Object anObject) :将此字符串与指定对象进⾏⽐较。
public boolean equalsIgnoreCase(String anotherString) :将此字符串与指定对象进
⾏⽐较,忽略⼤⼩写
⽅法演示,代码如下:
public class String_Demo01 {
public static void main(String[] args) {
// 创建字符串对象
String s1 = "hello";
String s2 = "hello";
String s3 = "HELLO";
// boolean equals(Object obj):⽐较字符串的内容是否相同
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
System.out.println("-----------");
// boolean equalsIgnoreCase(String str):⽐较字符串的内容是否相同,忽略
⼤⼩写
System.out.println(s1.equalsIgnoreCase(s2)); // true
System.out.println(s1.equalsIgnoreCase(s3)); // true
System.out.println("-----------");
} }
3.2获取功能的⽅法
public int length() :返回此字符串的⻓度。
public String concat(String str) :将指定的字符串连接到该字符串的末尾。
public char charAt(int index) :返回指定索引处的char值。
public int indexOf(String str) :返回指定⼦字符串第⼀次出现在该字符串内的索引。
public String substring(int beginIndex) :返回⼀个⼦字符串,从beginIndex开始截
取字符串到字符串结尾。
public String substring(int beginIndex, int endIndex) :返回⼀个⼦字符串,从
beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。
public class String_Demo02 {
public static void main(String[] args) {
// 创建字符串对象
String s = "helloworld";
// int length():获取字符串的⻓度,其实也就是字符个数
System.out.println(s.length());
System.out.println("--------");
// String concat (String str):将将指定的字符串连接到该字符串的末尾
s = "helloworld";
String s2 = s.concat("**hello bonnie");
System.out.println(s2); // helloworld**hello bonnie
// char charAt(int index):获取指定索引处的字符
System.out.println(s.charAt(0));
System.out.println(s.charAt(1));
System.out.println("--------");
// int indexOf(String str):获取str在字符串对象中第⼀次出现的索引,没有返
回-1
System.out.println(s.indexOf("l"));
System.out.println(s.indexOf("owo"));
System.out.println(s.indexOf("ak"));
System.out.println("--------");
// String substring(int start):从start开始截取字符串到字符串结尾
System.out.println(s.substring(0));
System.out.println(s.substring(5));
System.out.println("--------");
// String substring(int start, int end):从start到end截取字符串。含
start,不含end。
System.out.println(s.substring(0, s.length()));
System.out.println(s.substring(3,8));
} }
3.3转换功能的⽅法
public char[] toCharArray() :将此字符串转换为新的字符数组。
public byte[] getBytes() :使⽤平台的默认字符集将该String编码转换为新的字节数
组。
public String replace(CharSequence target, CharSequence replacement) :将与
target匹配的字符串使⽤replacement字符串替换
CharSequence 是⼀个接⼝,也是⼀种引⽤类型。作为参数类型,可以把String对象传
递到⽅法中。
public class String_Demo03 {
public static void main(String[] args) {
// 创建字符串对象
String s = "abcde";
// char[] toCharArray():把字符串转换为字符数组
char[] chs = s.toCharArray();
for (int x = 0; x < chs.length; x++) {
System.out.println(chs[x]);
}
System.out.println("-----------");
// byte[] getBytes ():把字符串转换为字节数组
byte[] bytes = s.getBytes();
for (int x = 0; x < bytes.length; x++) {
System.out.print(bytes[x]+" "); /* 97 98 99 100 101*/
}
System.out.println("-----------");
// 替换字⺟liu为⼤写Liu
String str = "bonnie liu";
String replace = str.replace("liu", "Liu");
System.out.println(replace); // bonnie Liu
System.out.println("-----------");
} }
3.4 分割功能的⽅法
public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符
串数组。
public class String_Demo03 {
public static void main(String[] args) {
// 创建字符串对象
String s = "aa|bb|cc";
String[] strArray = s.split("|"); // ["aa","bb","cc"]
for (int x = 0; x < strArray.length; x++) {
System.out.println(strArray[x]); // aa bb cc
}
} }
3.5 String类的练习
拼接字符串
定义⼀个⽅法,把数组 {1, 2, 3} 按照指定个格式拼接成⼀个字符串。输出结果如下:
[1#2#3]。
public class Demo {
public static void main(String[] args) {
// 定义⼀个int类型的数组
int[] arr = {1, 2, 3};
// 调⽤⽅法
String s = arrayToString(arr);
// 输出结果
System.out.println("s:" + s);
}
/*
* 写⽅法实现把数组中的元素按照指定的格式拼接成⼀个字符串
* 两个明确:
* 返回值类型: String
* 参数列表: int[] arr
*/
public static String arrayToString(int[] arr) {
// 创建字符串s
String s = new String("[");
// 遍历数组,并拼接字符串
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
s = s.concat(arr[x] + "]");
} else {
s = s.concat(arr[x] + "#");
}
}
return s;
}
}
统计字符个数
键盘录⼊⼀个字符,统计字符串中⼤⼩写字⺟及数字字符个数
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
// 键盘录⼊⼀个字符串数据
Scanner sc = new Scanner(System.in);
System.out.println("请输⼊⼀个字符串数据:");
String s = sc.nextLine();
// 定义三个统计变量,初始化值都是0
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
// 遍历字符串,得到每⼀个字符
for (int x = 0; x < s.length(); x++) {
char ch = s.charAt(x);
// 拿字符进⾏判断
if (ch >= 'A' && ch <= 'Z') {
bigCount++;
} else if (ch >= 'a' && ch <= 'z') {
smallCount++;
} else if (ch >= '0' && ch <= '9') {
numberCount++;
} else {
System.out.println("该字符" + ch + "⾮法");
}
}
// 输出结果
System.out.println("⼤写字符:" + bigCount + "个");
System.out.println("⼩写字符:" + smallCount + "个");
System.out.println("数字字符:" + numberCount + "个");
}
}
统计字符串里每个字母出现的次数
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
int[] count = new int[100]; //用来存储字母a-z A-Z出现的次数。
for(int i=0; i<str.length(); i++){
char tmp = str.charAt(i); //依次取出每个字母
if((tmp>=65&& tmp<=90)||(tmp>=97&& tmp<=122)){
int index = tmp - 65; //利用ascii码表,最小结果是0.
count[index] = count[index] + 1;
}
}
//循环打印每个字母出现次数
for(int j=0; j<count.length; j++){
if(count[j]!=0)
System.out.println("字母"+(char)(j+65)+"出现次数:"+count[j]);
}
}
}
## 4 可变长字符串StringBuilder, StringBuffer :
### 4.1 字符串拼接问题
由于String类的对象内容不可改变,所以每当进⾏字符串拼接时,总是会在内存中创建⼀个新的
对象。例如:
```java
public class StringDemo {
public static void main(String[] args) {
String s = "Hello";
s += "World";
System.out.println(s);
}
}
在API中对String类有这样的描述:字符串是常量,它们的值在创建后不能被更改
根据这句话分析我们的代码,其实总共产⽣了三个字符串,即== “Hello” 、 “World” 和 “HelloWorld” 。==引⽤变量s⾸先指向 Hello 对象,最终指向拼接出来的新字符串对象,即 HelloWord 。
由此可见,如果对字符串进行拼接操作,每次拼接,都会创建一个新的String对象,既耗时,又浪费时间 ,为了解决这一问题,可以使用java.lang.StringBuilder类。
4.2 StringBuilder概述
查阅 java.lang.StringBuilder 的API,StringBuilder⼜称为可变字符序列,它是⼀个类似于String 的字符串缓冲区,通过某些⽅法调⽤可以改变该序列的⻓度和内容。原来StringBuilder是个字符串的缓冲区,即它是⼀个容器,容器中可以装很多字符串。并且能够对其中的字符串进⾏各种操作。它的内部拥有⼀个数组⽤来存放字符串内容,进⾏字符串拼接时,直接在数组中加⼊新内容.StringBuilder会⾃动维护数组的扩容。原理如下图所示:(默认16字符空间,超过⾃动扩充)
4.3 构造⽅法StringBuilder常⽤的⽅法
1.public StringBuilder append(…) :添加任意类型数据的字符串形式,并返回当前对象
⾃身。
2.public String toString() :将当前StringBuilder对象转换为String对象。
append⽅法
append⽅法具有多种重载形式,可以接收任意类型的参数。任何数据作为参数都会将对应的字
符串内容添加到StringBuilder中。例如
public class Demo02StringBuilder {
public static void main(String[] args) {
//创建对象
StringBuilder builder = new StringBuilder();
//public StringBuilder append(任意类型)
StringBuilder builder2 = builder.append("hello");
//对⽐⼀下
System.out.println("builder:" + builder);
System.out.println("builder2:" + builder2);
System.out.println(builder == builder2); //true
// 可以添加 任何类型
builder.append("hello");
builder.append("world");
builder.append(true);
builder.append(100);
// 在我们开发中,会遇到调⽤⼀个⽅法后,返回⼀个对象的情况。然后使⽤返回的对象
继续调⽤⽅法。
// 这种时候,我们就可以把代码现在⼀起,如append⽅法⼀样,代码如下
//链式编程
builder.append("hello").append("world").append(true).append(100);
System.out.println("builder:" + builder);
} }
toString⽅法
通过toString⽅法,StringBuilder对象将会转换为不可变的String对象。如:
public class Demo16StringBuilder {
public static void main(String[] args) {
// 链式创建
StringBuilder sb = new
StringBuilder("Hello").append("World").append("Java");
// 调⽤⽅法
String str = sb.toString();
System.out.println(str); // HelloWorldJava
}
}
4.4 StringBuffer 和 StringBuilder 异同
-
相同:属于可变长字符串,也就是在创建新的字符串的时候不会产生新的对象
2 .区别
StringBuffer ——jdk 1.0
StringBulide ——jdk 1.5线程安全
StringBulider :线程不安全,效率高
StringBuffer :线程安全,效率不高使用环境
少量拼接使用String
单线程环境操作大量数据使用StringBuilder
多线程环境操作大量数据使用StringBuffer创建
new StringBuilder()
new StringBuffer();
常用API
1.append(Object obj) -追加(拼接)
2.删除 delete(int start, int end) 前包含,后不包含
3. insert(int offset,char c)
4. reverse(); 反转
StringBuilder案例
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
//append()拼接
sb.append("Runoob..");
System.out.println(sb);
sb.append("!");
System.out.println(sb);
//insert()插入
sb.insert(8, "Java");
System.out.println(sb);
//delete() 删除
sb.delete(5, 8);
System.out.println(sb);
//反转 reverse()
sb.reverse();
System.out.println(sb);
}
/*Runoob..
Runoob..!
Runoob..Java!
RunooJava!
!avaJoonuR*/
}
StringBuffer案例
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
//append()拼接
sb.append("Runoob..");
System.out.println(sb);
sb.append("!");
System.out.println(sb);
//insert()插入
sb.insert(8, "Java");
System.out.println(sb);
//delete() 删除
sb.delete(5,8);
System.out.println(sb);
//反转 reverse()
sb.reverse();
System.out.println(sb);
}
/*Runoob..
Runoob..!
Runoob..Java!
RunooJava!
!avaJoonuR*/
}