Java String 类
后面学习中 String 类的使用是非常重要的,其中包含许多的方法,所以就做了一些常用方法的总结
在java编程中,字符串使用非常广泛,在java中字符串属于对象,java提供了String类来创建和操作字符串。
1. 创建字符串
1.1 通过定义 String类型的变量创建字符串
String str = "I am a student";
1.2 通过构造器来创建 String 类型的字符串变量
String str = new String("abc");
2. String 常用的方法
2.1 charAt(int index)
功能:用于返回指定索引处的字符,范围 0 ~ length()-1
public class TestString {
public static void main(String[] args) {
String str = "I am a student!";
char c = str.charAt(3);
System.out.println(c);
}
}
运行结果为:m
2.2 compareTo(Object O[String anotherString]),compareTolgnoreCase(String str)
compareTo()功能:1. 用于字符串与对象进行比较,2. 按字典顺序比较两个字符串
compareTolgnoreCase()功能:用于按字典顺序比较两个字符串,不考虑大小写
返回值:整型 int,先比较对应字符串大小(ASCII码顺序),如果第一个字符和参数第一个字符不等,结束比较返回两个字符的 差值,如果第一个字符和参数第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推直到比较字符或被比较的字符有一方结束
- 如果参数字符串与字符串相等,返回0
- 如果字符串大于参数字符串,则返回一个大于0的值
- 如果字符串小于参数字符串,则返回一个小于0的值
public class TestString {
public static void main(String[] args) {
String str = "strs";
String str1 = "strs";
String str2 = "strs111";
int i = str.compareTo(str1);
System.out.println(i);
int i1 = str1.compareTo(str2);
System.out.println(i1);
int i2 = str2.compareTo(str);
System.out.println(i2);
}
}
运行结果:
0
-3
3
2.3 concat(String str)
功能:用于将指定的字符串参数连接到字符串上,等同于字符串连接的 + 号
public class TestString {
public static void main(String[] args) {
String str = "I am a ";
String student = str.concat("student");
System.out.println(student);
}
}
运行结果:I am a student
2.4 equals()
2.4.1 equals(Object anObject)
功能:用于将字符串与指定的对象比较
返回值:两个字符串相等返回 true,否则返回 false
public class TestString {
public static void main(String[] args) {
String str1 = "aaa";
String str2 = "bbb";
String str3 = "aaa";
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
}
}
运行结果:
false
true
2.4.2 contentEquals(StringBuffer sb)
功能:用于将此字符换与指定的 StringBuffer 比较
参数 sb 是要与字符串比较的StringBuffer
返回值:如果字符串与指定StringBuffer表示相同的字符序列,返回true,否则返回false
public class TestString {
public static void main(String[] args) {
String str1 = "aaa";
String str2 = "bbb";
StringBuffer str3 = new StringBuffer("ccc");
System.out.println(str1.contentEquals(str3));
System.out.println(str1.contentEquals(str2));
}
}
运行结果:
false
false
2.4.3 copyValueOf()
两种形式:1. public static String copyValueOf(char[] data):返回指定数组中表示该字符序列的字符串
2. public static String copyValueOf(char[] data, int offset, int count):返回指定数组中表示该字符序列的字符换。
参数:
- data 字符数组
- offset 子数组的初始偏移量
- count 子数组的长度
返回值:返回指定数组中表示该字符序列的字符串
public class TestString {
public static void main(String[] args) {
char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
String Str2 = "";
Str2 = Str2.copyValueOf( Str1 );
System.out.println("返回结果:" + Str2);
Str2 = Str2.copyValueOf( Str1, 2, 6 );
System.out.println("返回结果:" + Str2);
}
}
运行结果:
返回结果:hello world
返回结果:llo wo
2.4.4 endsWith(String suffix)
功能:用于测试字符串是否以指定的后缀结束
参数:suffix 指定的后缀
public class TestString {
public static void main(String[] args) {
String string = new String("I am a student");
System.out.println(string.endsWith("student"));
System.out.println(string.endsWith("aaaaaa"));
}
}
运行结果:
true
false
2.4.3 equalsIgnoreCase(String anotherString)
功能:用于将字符串与指定的对象比较,不考虑大小写
参数:anotherString 与字符串进行比较的对象
返回值:如果相等返回true,否则false
public class TestString {
public static void main(String[] args) {
String str1 = new String("student");
String str2 = new String("STUDENT");
System.out.println(str1.equalsIgnoreCase(str2));
}
}
运行结果:
true
2.5 getBytes()
该方法有两种形式
-
get Bytes(String charsetName):使用指定字符集将字符串编码为 byte 序列,并将结果存储到一个新的byte数组中
**参数:**charsetName 支持的字符集名称
-
getBytes():使用平台的默认字符集将字符串编码为byte序列,并将结果存储到一个新的byte数组中
public class TestString {
public static void main(String[] args) {
String str1 = new String("student");
System.out.println(str1.getBytes());
try {
System.out.println(str1.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
运行结果:
[B@1540e19d
[B@677327b6
2.6 getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
功能:将字符串从字符串复制到目标字符数组
参数:
- srcBegin:字符串中要复制的第一个字符的索引
- srcEnd:字符串中要复制的最后一个字符之后的索引
- dst:目标属组
- dstBegin:目标数组中的起始偏移量
返回值:没有返回值,会抛出 indexOutOfBoundsException异常
public class TestString {
public static void main(String[] args) {
String str1 = new String("student");
char[] str2 =new char[6];
str1.getChars(0,6,str2,0);
System.out.println(str2);
}
}
运行结果:
studen
2.7 hashCode()
功能:用于返回字符串的哈希码
哈希码计算公式:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
使用字符的int进行计算,s[i]是字符串的第i个字符,n是字符串的长度,^表示求幂,空字符串的哈希值为0
没有参数,
返回值:对象的哈希码值
public class TestString {
public static void main(String[] args) {
String str1 = new String("AB");
System.out.println(str1.hashCode());
}
}
运行结果:
2081
65 * 31^1 + 66
2.8 indexOf()
四种形式:
- public int indexOf(int ch):返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,返回 -1
- public int indexOf(int ch, int fromlndex):返回从 formlndex 位置开始查找指定字符串中第一次出现处的索引,如果没有 返回 -1
- int indexOf(String str):返回指定字符串在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,返回 -1
- int indexOf(String str, int fromlndex):返回从fromlndex位置开始查找指定字符在字符串中第一次出现处的索引,如果没有返回 -1
参数:
- ch 字符,Unicode编码
- fromIndex 开始搜索的索引位置,第一个字符是 0,第二个是 1,以此类推
- str 要搜索的子字符串
返回值:查找字符串,或字符Unicode编码在字符串中出现的位置
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.indexOf("a"));
System.out.println(str1.indexOf("a", 4));
System.out.println(str1.indexOf("am"));
System.out.println(str1.indexOf("am", 4));
}
}
运行结果:
2
5
2
-1
2.9 intern()
功能:返回字符串对象的规范化表示形式
遵循规则:对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 为 true
没有参数
返回值:一个字符串,内容与此字符串相同,但一定取自具有唯一字符串的池
public class TestString {
public static void main(String[] args) {
String str1 = "a";
String str2 = "b";
String str3 = "ab";
String str4 = str1 + str2;
String str5 = new String("ab");
System.out.println(str5.equals(str3));
System.out.println(str5 == str3);
System.out.println(str5.intern() == str3);
}
}
运行结果:
true
false
true
false
分析:第一个输出不要解释,因为字符串的值的内容相同
第二个 str5 == str3 对比的是引用的地址是否相同,str5是new String方式定义的,所以地址引用一定不相等,所以为 false
第三个 str5调用intern会检查字符串池中是否含有该字符串,由于之前定义的str3已经进入字符串池中,所以会得到相同的引用
2.10 lastIndexOf()
四种形式:
- 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:要搜索的子字符串
返回值:指定子字符串在字符串中第一次出现处的索引值
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.lastIndexOf("a"));
System.out.println(str1.lastIndexOf("a", 4));
System.out.println(str1.lastIndexOf("am"));
System.out.println(str1.lastIndexOf("am", 4));
}
}
运行结果:
5
2
2
2
2.11 length()
功能:用于返回字符串的长度,空字符串返回 0
没有参数
返回值:返回字符串的长度
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.length());
}
}
返回结果:
14
2.12 mathces(regex, str)
功能:用于检测字符串是否匹配给定的正则表达式,调用此方法 str.mathces(regex)形式与以下表达式产生的结果完全相同:Pattern.mathces(regex, str)
参数:
- regex:匹配字符串的正则表达式
返回值:在字符串匹配给定的正则表达式时,返回 true
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.matches("(.*)am(.*)"));
}
}
返回结果:
true
2.13 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:要比较的字符数
返回值:如果字符串的指定子区域匹配字符串参数的指定子区域,则返回true,否则返回false,是否完全匹配或考虑大小写取决于 ignoreCase 参数
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
String str2 = new String("student");
String str3 = new String("STUDENT");
System.out.println(str1.regionMatches(7, str2, 0, 7));
System.out.println(str1.regionMatches(true, 7, str3, 0, 7));
}
}
返回结果:
true
true
2.14 eplace(),replaceAll(),repalceFirst()
2.14.1replace(char searchChar, char newChar)
功能:通过newChar字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串
参数:
- searchChar:原字符
- newChar:新字符
返回值:替换后生成的新字符串
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.replace("student", "teacher"));
}
}
返回结果:
I am a teacher
2.14.2 replaceAll(String regex, String replacement)
功能:使用给定参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串
参数:
- regex:匹配此字符串的正则表达式
- newChar:用来替换每个匹配项的字符串
返回值:成功则返回替换的字符串,失败则返回原始字符串。
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.replaceAll("(.*)student(.*)", "teacher"));
System.out.println(str1.replaceAll("(.*)aaaaaa(.*)", "teacher"));
}
}
运行结果:
teacher
I am a student
2.14.3 replaceFirst(String regex, String replacement)
功能:使用给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串
参数:
- regex:匹配此字符串的正则表达式
- replacement:用来替换第一个匹配项的字符串
返回值:成功则返回替换的字符串,失败则返回原始字符串
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.replaceFirst("(.*)student(.*)", "teacher"));
System.out.println(str1.replaceFirst("(.*)aaaaaa(.*)", "teacher"));
}
}
运行结果:
teacher
I am a student
2.15 split(String regex, int limit)
功能:根据匹配给定的正则表达式来拆分字符串
注意:. $ | * 等转义字符,必须得加 \ \ ,多个分隔符可以用 | 作为连字符
参数:
- regex:正则表达式分隔符
- limit:分隔的份数
返回值:字符串数组
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
for (String s : str1.split(" ")) {
System.out.println(s);
}
String str2 = new String("I am a studentandI am a teacher");
for (String s : str2.split(" |and")) {
System.out.println(s);
}
}
}
运行结果:
I
am
a
student
I
am
a
student
I
am
a
teacher
2.16 startsWith()
功能:用于检测字符串是否以指定的前缀开始
两种形式:
- public boolean startsWith(String prefix, int toffset)
- public boolean startsWith(String prefix)
参数:
- prefix:前缀
- toffset:字符串中开始查找的位置
返回值:如果字符串以指定的前缀开始,则返回 true,否则返回false
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a studentandI am a teacher");
System.out.println(str1.startsWith("I"));
System.out.println(str1.startsWith("a", 5));
}
}
运行结果:
true
true
2.17 subSequence(int beginIndex, int endIndex)
功能:返回一个新的字符序列,它是此序列的一个子序列
参数:
- beginIndex:起始索引(包括)
- endIndex:结束索引(不包括)
返回值:返回一个新的字符序列,它是此序列的一个子序列
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.subSequence(7, 14));
}
}
运行结果:
student
2.18 substring()
功能:返回字符串的子字符串
两种形式:
- public String substring(int beginIndex)
- public String substring(int beginIndex, int endIndex)
参数:
- beginIndex:起始索引(包括),索引从0开始
- endIndex:结束索引(不包括)
返回值:子字符串
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.substring(7, 14));
System.out.println(str1.substring(0));
}
}
运行结果:
student
I am a student
2.19 toCharArray()
功能:将字符串转换为字符数组
没有参数
返回值:字符数组
public class TestString {
public static void main(String[] args) {
String str1 = new String("student");
for (char c : str1.toCharArray()) {
System.out.println(c);
}
}
}
运行结果:
s
t
u
d
e
n
t
2.20 大小写转换
2.20.1 toLowerCase()
功能:将字符串转换为小写
没有参数
返回值:转换为小写字符串
public class TestString {
public static void main(String[] args) {
String str1 = new String("STUDENT");
System.out.println(str1.toLowerCase());
}
}
运行结果:
student
2.20.2 toUpperCase()
功能:将字符串小写字符转换为大写
没有参数
返回值:字符转换为大写后的字符串
public class TestString {
public static void main(String[] args) {
String str1 = new String("student");
System.out.println(str1.toUpperCase());
}
}
运行结果:
STUDENT
2.21 toString()
功能:返回此对象本身(它已经是一个字符串)
返回值:字符串本身
public class TestString {
public static void main(String[] args) {
String str1 = new String("student");
System.out.println(str1.toString());
}
}
运行结果:
student
2.22 trim()
功能:删除字符串的头尾空白符
返回值:删除头尾空白符的字符串
public class TestString {
public static void main(String[] args) {
String str1 = new String(" student ");
System.out.println(str1);
System.out.println(str1.trim());
}
}
运行结果:
student
student
2.23 valueOf()
功能:返回各返回值的字符串表示形式
形式:
- valueOf(boolean b):返回boolean参数的字符串表示形式
- valueOf(char c):返回 char 参数的字符串表示形式
- valueOf(char[] data):返回char数组参数的字符串表示形式
- valueOf(char[] data, int offset, int coutn):返回 char 数组参数的特定子数组的字符串表示形式
- valueOf(double d):返回double参数的字符串表示形式
- valueOf(float f):返回 float 参数的字符串表示形式
- valueOf(int i):返回 int 参数的字符串表示形式
- valueOf(long I):返回 long 参数的字符串表示形式
- valueOf(Object obj):返回Object参数的字符串表示形式
参数:指定参数
返回值:返回指定参数的字符串表示形式
public class TestString {
public static void main(String[] args) {
double d = 1100.00;
boolean b = true;
long l = 1234567890;
char[] arr = {'s', 't', 'u', 'd', 'e', 'n','t' };
System.out.println(String.valueOf(d) );
System.out.println(String.valueOf(b) );
System.out.println(String.valueOf(l) );
System.out.println(String.valueOf(arr) );
}
}
运行结果:
1100.0
true
1234567890
student
2.24 contains(CharSequence chars)
功能:用于判断字符串中是否包含指定的字符或字符串
参数:
- chars:要判断的字符或字符串
返回值:如果包含指定的字符或字符串返回true,否则返回false
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
System.out.println(str1.contains("am"));
}
}
运行结果:
true
2.25 isEmpty()
功能:用于判断字符串是否为空
没有参数
返回值:如果字符串为空返回true,否则返回false,字符串通过 length() 方法计算字符串长度,如果返 回0,即为空字符串
public class TestString {
public static void main(String[] args) {
String str1 = new String("I am a student");
String str2 = new String();
System.out.println(str1.isEmpty());
System.out.println(str2.isEmpty());
}
}
运行结果:
false
true