Java String 类
1、创建字符串
使用三种方法创建字符串,一种是String直接创建,另一种是String对象创建,还有这一种是通过字符数组参数创建字符串。
package String;
public class CreateString {
public static void main(String[] args) {
String str1 = "雨打梨花深闭门,";
String str2 = new String("忘了青春,");
String str3 = new String("误了青春。");
System.out.println(str1 + str2 + str3);
char[] poem = {'唐', '寅', '《', '一', '剪', '梅', '》'};
String str4 = new String(poem);
System.out.println(str4);
}
}
/*
雨打梨花深闭门,忘了青春,误了青春。
唐寅《一剪梅》
*/
2、字符串的长度
字符串的长度使用length()方法返回。
package String;
public class StringLength {
public static void main(String[] args) {
String str = "人面不知何处去,桃花依旧笑春风";
int stringLength = str.length();
System.out.println(stringLength);
}
}
/*
15
*/
3、连接字符串
连接字符串使用两种方法实现,第一种使用concat连接,第二种使用+连接。
package String;
public class ConnectString {
public static void main(String[] args) {
String str1 = "林花谢了春红,太匆匆。";
String str2 = "无奈朝来寒雨晚风中。";
System.out.println(str1.concat(str2));
String str3 = new String("行到水穷处,");
String str4 = new String("坐看云起时。");
System.out.println(str3 + str4);
}
}
/*
林花谢了春红,太匆匆。无奈朝来寒雨晚风中。
行到水穷处,坐看云起时。
*/
4、创建格式化字符串
printf形式:
System.out.printf("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", floatVar, intVar, stringVar);
format形式
String fs;
fs = String.format("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
" %s", floatVar, intVar, stringVar);
5、String 方法
5.1charAt() 方法
char charAt(int index),charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。
package String;
public class CharAt {
public static void main(String[] args) {
String str = "今人不见古时月,今月曾经照古人";
char ch = str.charAt(6);
System.out.println(ch);
}
}
/*月*/
5.2 & 5.3 compareTo() 方法
compareTo() 方法用于两种方式的比较:
- 字符串与对象进行比较。
- 按字典顺序比较两个字符串。
返回值:
返回值是整型,它是先比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的长度差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方结束。
- 如果参数字符串等于此字符串,则返回值 0;
- 如果此字符串小于字符串参数,则返回一个小于 0 的值;
- 如果此字符串大于字符串参数,则返回一个大于 0 的值。
package String;
public class CompareTo {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "hello";
String str3 = "helloWorld";
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str3));
System.out.println(str3.compareTo(str2));
}
}
/*
0
-5
5
*/
5.4 compareToIgnoreCase() 方法
compareToIgnoreCase() 方法用于按字典顺序比较两个字符串,不考虑大小写。
package String;
public class CompareToIgnoreCase {
public static void main(String[] args) {
String str1 = "HELLO";
String str2 = "hello";
String str3 = "helloWORLD";
System.out.println(str1.compareToIgnoreCase(str2));
System.out.println(str1.compareToIgnoreCase(str3));
System.out.println(str3.compareToIgnoreCase(str2));
}
}
/*
0
-5
5
*/
5.5 concat() 方法
concat() 方法用于将指定的字符串参数连接到字符串上。
package String;
public class Concat {
public static void main(String[] args) {
String str1 = "自在飞花轻似梦,";
String str2 = "无边丝雨细如愁。";
System.out.println(str1.concat(str2));
}
}
/*自在飞花轻似梦,无边丝雨细如愁。*/
5.6 contentEquals() 方法
contentEquals() 方法用于将此字符串与指定的 StringBuffer 比较。
语法:
public boolean contentEquals(StringBuffer sb)
package String;
public class ContentEquals {
public static void main(String[] args) {
String str1 = "漠漠轻寒上小楼";
String str2 = "晓阴无赖似穷秋";
StringBuffer str3 = new StringBuffer("晓阴无赖似穷秋");
System.out.println(str1.contentEquals(str3));
System.out.println(str2.contentEquals(str3));
}
}
/*
false
true
*/
5.7 & 5.8 copyValueOf() 方法
copyValueOf() 方法有两种形式:
- public static String copyValueOf(char[] data): 返回指定数组中表示该字符序列的字符串。
- public static String copyValueOf(char[] data, int offset, int count): 返回指定数组中表示该字符序列的 字符串。
offset – 子数组的初始偏移量。count – 子数组的长度。
package String;
public class CopyValueOf {
public static void main(String[] args) {
char[] ch = {'淡', '烟', '流', '水', '画', '屏', '幽'};
String str = "";
System.out.println(str.copyValueOf(ch));
System.out.println(str.copyValueOf(ch, 4, 3));
}
}
/*
淡烟流水画屏幽
画屏幽
*/
5.9 endsWith() 方法
endsWith() 方法用于测试字符串是否以指定的后缀结束。如果参数表示的字符序列是此对象表示的字符序列的后缀,则返回 true;否则返回 false。注意,如果参数是空字符串,或者等于此 String 对象(用 equals(Object) 方法确定),则结果为 true。
package String;
public class EndsWith {
public static void main(String[] args) {
String str1 = "青山一道同云雨";
String str2 = "明月何曾是两乡";
System.out.println(str1.endsWith("雨"));
System.out.println(str2.endsWith("雨"));
}
}
/*
true
false
*/
5.10 equals() 方法
equals() 方法用于将字符串与指定的对象比较。
String 类中重写了 equals() 方法用于比较两个字符串的内容是否相等。
package String;
public class Equals {
public static void main(String[] args) {
String str1 = "沅水通波接武冈";
String str2 = "送君不觉有离伤";
String str3 = "送君不觉有离伤";
System.out.println(str1.equals(str2));
System.out.println(str2.equals(str3));
}
}
/*
false
true
*/
使用 == 和 equals() 比较字符串。
String 中 == 比较引用地址是否相同,equals() 比较字符串的内容是否相同:
package String;
public class EqualsAndEqualsSame {
public static void main(String[] args) {
String str1 = "小楼一夜听春雨,深巷明朝卖杏花。";
String str2 = "小楼一夜听春雨,深巷明朝卖杏花。";
String str3 = str1;
String str4 = new String("小楼一夜听春雨,深巷明朝卖杏花。");
String str5 = new String("小楼一夜听春雨,深巷明朝卖杏花。");
// == 比较引用地址是否相同
System.out.println(str1 == str1);
System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str1 == str4);
System.out.println(str4 == str5);
// equals() 比较字符串的内容是否相同
System.out.println("===============");
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
System.out.println(str1.equals(str4));
System.out.println(str4.equals(str5));
}
}
/*
true
true
true
false
false
===============
true
true
true
true
*/
5.11 equalsIgnoreCase() 方法
equalsIgnoreCase() 方法用于将字符串与指定的对象比较,不考虑大小写。
public boolean equalsIgnoreCase(String anotherString)
package String;
public class EqualsIgnoreCase {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "HELLO";
String str3 = str1;
String str4 = new String("hello");
String str5 = new String("HELLO");
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str2.equalsIgnoreCase(str3));
System.out.println(str1.equalsIgnoreCase(str4));
System.out.println(str3.equalsIgnoreCase(str4));
System.out.println(str4.equalsIgnoreCase(str5));
}
}
/*
true
true
true
true
true
*/
5.12 & 5.13 getBytes() 方法
getBytes() 方法有两种形式:
- getBytes(String charsetName): 使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
- getBytes(): 使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
package String;
import java.io.UnsupportedEncodingException;
public class GetBytes {
public static void main(String[] args) {
String str = new String("hello");
try {
System.out.println(str.getBytes());
System.out.println(str.getBytes("UTF-8"));
System.out.println(str.getBytes("ISO-8859-1"));
} catch (UnsupportedEncodingException e){
System.out.println("不支持的字符集!");
}
}
}
/*
[B@1b6d3586
[B@4554617c
[B@74a14482
*/
5.14 getChars() 方法
getChars() 方法将字符从字符串复制到目标字符数组。
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
参数
- srcBegin – 字符串中要复制的第一个字符的索引。
- srcEnd – 字符串中要复制的最后一个字符之后的索引。
- dst – 目标数组。
- dstBegin – 目标数组中的起始偏移量。
package String;
public class GetChars {
public static void main(String[] args) {
String str = "素衣莫起风尘叹,犹及清明可到家。";
char[] ch = new char[3];
try {
str.getChars(4, 7, ch, 0);
System.out.println(ch);
} catch (Exception e) {
System.out.println("触发异常!");
}
}
}
/*风尘叹*/
5.15 hashCode() 方法
hashCode() 方法用于返回字符串的哈希码。
字符串对象的哈希码根据以下公式计算:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。空字符串的哈希值为 0。
package String;
public class HashCode {
public static void main(String[] args) {
String str = "矮纸斜行闲作草,晴窗细乳戏分茶。";
System.out.println(str.hashCode());
}
}
/*1270220858*/
5.16 & 5.17 & 5.18 & 5.19 indexOf() 方法
返回指定字符在此字符串中第一次出现处的索引。
indexOf() 方法有以下四种形式:
- public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
package String;
public class IndexOf {
public static void main(String[] args) {
String str = "helloAaa123abc";
System.out.println(str.indexOf('l'));
System.out.println(str.indexOf('a'));
System.out.println(str.indexOf("a", 8));
System.out.println(str.indexOf(99));
System.out.println(str.indexOf('c'));
}
}
/*
2
6
11
13
13
*/
5.20 intern() 方法
intern() 方法返回字符串对象的规范化表示形式。
package String;
public class Intern {
public static void main(String[] args) {
String str = "溪云初起日沉阁,山雨欲来风满楼。";
String strNew = "hello WORLD";
System.out.println(str.intern());
System.out.println(strNew.intern());
}
}
/*
溪云初起日沉阁,山雨欲来风满楼。
hello WORLD
*/
5.21 & 5.22 & 5.23 & 5.34 lastIndexOf() 方法
astIndexOf() 方法有以下四种形式:
- public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。
- public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1。
参数:
- ch – 字符。
- fromIndex – 开始搜索的索引位置。
- str – 要搜索的子字符串。
package String;
public class LastIndexOf {
public static void main(String[] args) {
String str = "helloWWoorlld";
System.out.println(str.lastIndexOf('l'));
System.out.println(str.lastIndexOf('l', 9));
System.out.println(str.lastIndexOf('o'));
System.out.println(str.lastIndexOf("ll"));
System.out.println(str.lastIndexOf("ll", 3));
}
}
/*
11
3
8
10
2
*/
5.25 length() 方法
length() 方法用于返回字符串的长度。空字符串的长度返回 0。
package String;
public class Length {
public static void main(String[] args) {
String str = "二十四桥明月夜,玉人何处教吹箫?";
System.out.println(str.length());
}
}
/*16*/
5.26 matches() 方法
matches() 方法用于检测字符串是否匹配给定的正则表达式。
调用此方法的 str.matches(regex) 形式与以下表达式产生的结果完全相同:
Pattern.matches(regex, str)
regex – 匹配字符串的正则表达式。
package String;
public class Matches {
public static void main(String[] args) {
String str = "空山新雨后,天气晚来秋。";
System.out.println(str.matches("(.*)空山新雨后(.*)"));
System.out.println(str.matches("(.*)天气晚来秋(.*)"));
System.out.println(str.matches("(.*)山居秋暝(.*)"));
}
}
/*
true
true
false
*/
5.27 & 5.28 regionMatches() 方法
regionMatches() 方法用于检测两个字符串在一个区域内是否相等。
语法:
public boolean regionMatches(int toffset,
String other,
int ooffset,
int len)
或
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)
参数:
- ignoreCase – 如果为 true,则比较字符时忽略大小写。
- toffset – 此字符串中子区域的起始偏移量。
- other – 字符串参数。
- ooffset – 字符串参数中子区域的起始偏移量。
- len – 要比较的字符数。
package String;
public class RegionMatches {
public static void main(String[] args) {
String str = "helloWorld";
String str1 = "oWo";
String str2 = "OWO";
System.out.println(str.regionMatches(4, str1, 0, 2));
System.out.println(str.regionMatches(4, str2, 0, 2));
System.out.println(str.regionMatches(true, 4, str2, 0, 2));
}
}
/*
true
false
true
*/
5.29 replace() 方法
replace() 方法通过用 newChar 字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串。
public String replace(char searchChar, char newChar)
参数:
- searchChar – 原字符。
- newChar – 新字符。
package String;
public class Replace {
public static void main(String[] args) {
String str = "人言落日是天涯,望极天涯不见家。";
System.out.println(str.replace("天涯", "尽头"));
System.out.println(str.replace("落日", "沧海"));
}
}
/*
人言落日是尽头,望极尽头不见家。
人言沧海是天涯,望极天涯不见家
*/
5.30 replaceAll() 方法
replaceAll() 方法使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串。
public String replaceAll(String regex, String replacement)
参数:
- regex – 匹配此字符串的正则表达式。
- newChar – 用来替换每个匹配项的字符串。
package String;
public class ReplaceAll {
public static void main(String[] args) {
String str = "已恨碧山相阻隔,碧山还被暮云遮。";
System.out.println("匹配替换成功后,返回替换的字符串");
System.out.println(str.replaceAll("(.*)碧山(.*)", "大海"));
System.out.println("匹配替换失败后,返回原来的字符串");
System.out.println(str.replaceAll("(.*)青山(.*)", "大海"));
}
}
/*
匹配替换成功后,返回替换的字符串
大海
匹配替换失败后,返回原来的字符串
已恨碧山相阻隔,碧山还被暮云遮。
*/
5.31 replaceFirst() 方法
replaceFirst() 方法使用给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串。
public String replaceFirst(String regex, String replacement)
package String;
public class ReplaceFirst {
public static void main(String[] args) {
String str = "人言落日是天涯,望极天涯不见家。";
System.out.println(str.replaceFirst("天涯", "黑暗"));
System.out.println(str.replaceFirst("(,*)天涯(,*)", "黑暗"));
}
}
/*
人言落日是黑暗,望极天涯不见家。
人言落日是黑暗,望极天涯不见家。
*/
5.32 & 5.33 split() 方法
split() 方法根据匹配给定的正则表达式来拆分字符串。
注意: . 、 $、 | 和 ***** 等转义字符,必须得加 \。
**注意:**多个分隔符,可以用 | 作为连字符。
public String[] split(String regex, int limit)
参数:
- regex – 正则表达式分隔符。
- limit – 分割的份数。
package String;
public class Split {
public static void main(String[] args) {
String str = "我欲穿花寻路,直入白云深处,浩气展虹霓";
System.out.println("========分隔符返回值");
for (String string : str.split(",")) {
System.out.println(string);
}
System.out.println("========分隔符返回值设置份数");
for (String string : str.split(",", 2)) {
System.out.println(string);
}
System.out.println("========转义字符返回值");
for (String string : str.split("\\,", 3)) {
System.out.println(string);
}
System.out.println("========多个分隔符返回值");
String strNew = "我欲穿花寻路and直入白云深处or浩气展虹霓";
for (String string : strNew.split("and|or")) {
System.out.println(string);
}
}
}
/*
========分隔符返回值
我欲穿花寻路
直入白云深处
浩气展虹霓
========分隔符返回值设置份数
我欲穿花寻路
直入白云深处,浩气展虹霓
========转义字符返回值
我欲穿花寻路
直入白云深处
浩气展虹霓
========多个分隔符返回值
我欲穿花寻路
直入白云深处
浩气展虹霓
*/
5.34 & 5.35 startsWith() 方法
startsWith() 方法用于检测字符串是否以指定的前缀开始。
public boolean startsWith(String prefix, int toffset)
或
public boolean startsWith(String prefix)
参数:
- prefix – 前缀。
- toffset – 字符串中开始查找的位置。
package String;
public class StartsWith {
public static void main(String[] args) {
String str = "应是天仙狂醉,乱把白云揉碎。";
System.out.println(str.startsWith("应"));
System.out.println(str.startsWith("乱"));
System.out.println(str.startsWith("乱", 7));
}
}
/*
true
false
true
*/
5.36 subSequence() 方法
subSequence() 方法返回一个新的字符序列,它是此序列的一个子序列。
public CharSequence subSequence(int beginIndex, int endIndex)
package String;
public class SubSequence {
public static void main(String[] args) {
String str = "云中谁寄锦书来?雁字回时,月满西楼。";
System.out.println(str.subSequence(8, 18));
}
}
/*
雁字回时,月满西楼。
*/
5.37 & 5.38 substring() 方法
substring() 方法返回字符串的子字符串。
public String substring(int beginIndex)
或
public String substring(int beginIndex, int endIndex)
package String;
public class SubString {
public static void main(String[] args) {
String str = "风乍起,吹皱一池春水。闲引鸳鸯香径里,手挼红杏蕊。";
System.out.println(str.substring(11));
System.out.println(str.substring(4, 10));
}
}
/*
闲引鸳鸯香径里,手挼红杏蕊。
吹皱一池春水
*/
5.39 toCharArray() 方法
toCharArray() 方法将字符串转换为字符数组。
public char[] toCharArray()
package String;
public class ToCharArray {
public static void main(String[] args) {
String str = "明月出天山,苍茫云海间。";
System.out.println(str.toCharArray());
}
}
/*明月出天山,苍茫云海间。*/
5.40 & 5.41 toLowerCase() 方法
toLowerCase() 方法将字符串转换为小写。
public String toLowerCase()
或
public String toLowerCase(Locale locale)
package String;
import java.util.Locale;
public class ToLowerCase {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str.toLowerCase());
}
}
/*hello*/
5.42toString() 方法
toString() 方法返回此对象本身(它已经是一个字符串)。
package String;
public class ToString {
public static void main(String[] args) {
String str = "旧时茅店社林边,路转溪桥忽见。";
System.out.println(str.toString());
}
}
/*旧时茅店社林边,路转溪桥忽见。*/
5.43 & 5.44 toUpperCase() 方法
toUpperCase() 方法将字符串小写字符转换为大写。
public String toUpperCase()
或
public String toUpperCase(Locale locale)
package String;
import java.util.Locale;
public class ToUpperCase {
public static void main(String[] args) {
String str = "hello";
System.out.println(str.toUpperCase());
}
}
/*HELLO*/
5.45 trim() 方法
trim() 方法用于删除字符串的头尾空白符。
package String;
public class Trim {
public static void main(String[] args) {
String str = " 春潮带雨晚来急,野渡无人舟自横。 ";
System.out.println(str.trim());
}
}
/*春潮带雨晚来急,野渡无人舟自横。*/
5.46 valueOf() 方法
返回给定data type类型x参数的字符串表示形式。
valueOf() 方法有以下几种不同形式:
- valueOf(boolean b): 返回 boolean 参数的字符串表示形式。.
- valueOf(char c): 返回 char 参数的字符串表示形式。
- valueOf(char[] data): 返回 char 数组参数的字符串表示形式。
- valueOf(char[] data, int offset, int count): 返回 char 数组参数的特定子数组的字符串表示形式。
- valueOf(double d): 返回 double 参数的字符串表示形式。
- valueOf(float f): 返回 float 参数的字符串表示形式。
- valueOf(int i): 返回 int 参数的字符串表示形式。
- valueOf(long l): 返回 long 参数的字符串表示形式。
- valueOf(Object obj): 返回 Object 参数的字符串表示形式。
语法:
static String valueOf(boolean b)
或
static String valueOf(char c)
或
static String valueOf(char[] data)
或
static String valueOf(char[] data, int offset, int count)
或
static String valueOf(double d)
或
static String valueOf(float f)
或
static String valueOf(int i)
或
static String valueOf(long l)
或
static String valueOf(Object obj)
package String;
public class ValueOf {
public static void main(String[] args) {
int a = 123;
double b = 100.00;
float c = 12;
long d = 23456;
boolean e = true;
char[] f = {'缺', '月', '挂', '疏', '桐'};
System.out.println(String.valueOf(a));
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(c));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(e));
System.out.println(String.valueOf(f));
}
}
/*
123
100.0
12.0
23456
true
缺月挂疏桐
*/
5.47 contains() 方法
contains() 方法用于判断字符串中是否包含指定的字符或字符串。
package String;
public class Contains {
public static void main(String[] args) {
String str = "朔风如解意,容易莫摧残。";
System.out.println(str.contains("风"));
System.out.println(str.contains("容易"));
System.out.println(str.contains("梅花"));
}
}
/*
true
true
false
*/
5.48 isEmpty() 方法
isEmpty() 方法用于判断字符串是否为空。
package String;
public class IsEmpty {
public static void main(String[] args) {
String str1 = "水晶帘动微风起,满架蔷薇一院香。";
String str2 = "";
String str3 = " ";
System.out.println(str1.isEmpty());
System.out.println(str2.isEmpty());
System.out.println(str3.isEmpty());
}
}
/*
false
true
false
*/