概述
java.lang.String是最常用的类,表示字符串,可以理解为文字
Java程序中所有的字符串文字(例如 “abc” )都可以被看作是实现 此类的实例。
构造方法
String():无参
String(byte[]):把内存中一些字节数据转化成字符串,字节数据并不是指数字,是Java中运行直接操作的最小单位是byte,所以用byte数组表示一些二进制
String(byte[],编码集):将字节数组中的内容,以某个编码集的格式转化成字符串
String(char[]):字符数组转字符串。String底层是靠 字符数组 实现的。
String(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);
String str4=new String("abc");
简化创建对象
String str5="hello world";
常用方法
判断字符串内容是否相同
方法一:判断字符串内容是否相同,区分大小写
public boolean equals (Object anObject)
判断字符串和Object的值是否相同,这个方法是重写了Object的equals方法
内部执行会先判断地址是否相同,相同返回true,再判断Object是不是字符串数据类型,如果不是返回false,如果是字符串,那么比较两个字符串的内容是否相同
方法二:判断字符串内容是否相同,不区分大小写
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("‐‐‐‐‐‐‐‐‐‐‐");
}
}
获取功能的方法
- public int length () :返回此字符串的长度。
- public String concat (String str) :将指定的字符串连接到该字符串的末尾。
- public char charAt (int index) :返回指定索引处的 char值。
- public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
- lastIndexOf(String):返回String在字符串中从后向前找,第一次出现的索引,索引值仍然是从前向后数的索引
- 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):将将指定的字符串连接到该字符串的末尾.
String s = "helloworld";
String s2 = s.concat("**hello 测试");
System.out.println(s2);// helloworld**hello 测试
// 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));
}
}
转换功能的方法
- public char[] toCharArray () :将此字符串转换为新的字符数组。
- public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
- toLowerCase():返回字符串的小写
- toUpperCase():返回字符串的大小
- trim():去掉字符串前后的空格,但是不会去掉中间的空格
- public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使用replacement字符串替换。
- replaceAll(String1,String2):将字符串中所有满足String1正则表达式的字符串替换成String2。返回值是替换后的字符串,不会修改原始字符串
例子:
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.println(bytes[x]); }
System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); // 替换字母it为大写IT
String str = "李雷、李四";
String replace = str.replace("李", "王");
System.out.println(replace);
}
}
CharSequence 是一个接口,也是一种引用类型。作为参数类型,可以把String对象传递到方法中。
分割功能的方法
- public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。
例子:
有下面字符串:
李雷、韩梅梅、lucy、lili
通过编程算出有几个人?
分析:人名是根据 、 间隔的,可以使用 split() 方法拆分字符串
public class String_Demo03 {
public static void main(String[] args) {
String s = "李雷、韩梅梅、lucy、lili";
String[] arr = s.split("、");
System.out.println(arr.length);
}
}
其他
- isEmpty():返回字符串是否为空,当length()为0时返回true。判断一个字符串是否为空时,一定有两个条件,第一个条件String==null,第二个条件isEmpty()。
练习
拼接字符串
定义一个方法,把数组{1,2,3}按照指定个格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。
public class StringTest1 {
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;
}
}
统计字符个数
键盘录入一个字符,统计字符串中大小写字母及数字字符个数
public class StringTest2 {
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+"个");
}
}
特点
字符串不变
字符串的值在创建后不能被更改,对字符串做拼接,都会创建一个新的字符串对象
所以不要频繁拼接String字符串,速度慢,内存占用大
String s1 = "abc";
s1 += "d";
System.out.println(s1); // "abcd"
// 内存中有"abc","abcd"两个对象,s1从指向"abc",改变指向,指向了"abcd"。
可以共享
例子1:
String a="hello world";
String b="hello world";
System.out.println(a==b);
内存中只有1个"hello world"对象,同时被 a 和 b 共享。
例子2:
//创建"hello world"对象
String a="hello world";
//使用new关键字,创建"hello world"对象
String b=new String("hello world");
System.out.println(a==b);
内存中有2个"hello world"对象