目录
String类
1.声明字符串
- 语法格式:String s;
声明字符串变量必须初始化才能使用,否则编译器会报出“变量未初始化错误:
2.创建字符串
String类常用的构造方法如下:
1.String(char a[])
用一个字符数组a创建String对象
2.String(char a[] ,int ofset,int length)
提取字符数组a中的一部分创建一个字符数组对象。参数ofset表示开始截取字符串的位置,length表示截取字符串的长度。
3.String(char[] value)
该构造方法可分配一个新的String对象,使其表示字符数组参数中所有元素连接的结果
3.了解字符串
1.连接多个字符串
要连接多个字符串,您可以使用“+”运算符或字符串方法“join()”。以下是两种方法的示例:
使用“+”运算符:
str1 = "Hello"
str2 = "World"
str3 = "!"
result = str1 + " " + str2 + str3
print(result)
# Output: "Hello World!"
使用“join()”方法:
str1 = "Hello"
str2 = "World"
str3 = "!"
result = " ".join([str1, str2, str3])
print(result)
# Output: "Hello World!"
请注意,在使用“join()”方法时,您需要先将所有字符串放入一个列表中,并使用分隔符作为参数传递给“join()”方法。在这个例子中,我们使用空格作为分隔符。
2.连接其它数据类型
连接其他数据类型时,您需要使用类型转换来将它们转换为字符串。以下是几个示例:
连接整数和字符串:
num = 42
str1 = "The answer is: "
result = str1 + str(num)
print(result)
# Output: "The answer is: 42"
连接浮点数和字符串:
pi = 3.14159
str1 = "The value of pi is: "
result = str1 + str(pi)
print(result)
# Output: "The value of pi is: 3.14159"
连接布尔值和字符串:
is_raining = True
str1 = "Is it raining? "
result = str1 + str(is_raining)
print(result)
# Output: "Is it raining? True"
在这些示例中,我们使用了“+”运算符来连接字符串和其他数据类型。我们还使用了“str()”函数来将其他数据类型转换为字符串。
获取字符串信息
1.获取字符串的长度
获取字符串的长度可以使用内置函数len()
。这个函数可以计算出字符串中字符的总数,包括空格、标点符号和其他特殊字符。以下是一个简单的示例:
string = "Hello, world!"
length = len(string)
print(length)
# Output: 13
在这个例子中,我们定义了一个字符串变量“string”,使用len()函数来获取字符串的长度,并将结果存储在变量“length”中。最后,我们使用print()函数来输出字符串的长度。
2.字符串查找
在Java中,你可以使用indexOf()
或lastIndexOf()
函数来查找一个字符串中是否包含另一个字符串。
两个函数的基本用法相同,都需要指定要查找的子字符串,可以指定要开始查找的位置,如果找到了,返回这个子字符串在原字符串中的起始位置;如果没找到,indexOf()
函数返回-1,lastIndexOf()
函数返回-1。
示例代码如下:
String string = "Hello, world!";
String target = "world";
// 使用 indexOf() 函数查找
int pos = string.indexOf(target);
if (pos != -1) {
System.out.println("Found '" + target + "' at position " + pos);
} else {
System.out.println("'" + target + "' not found");
}
// 使用 lastIndexOf() 函数查找
pos = string.lastIndexOf(target);
if (pos != -1) {
System.out.println("Found '" + target + "' at position " + pos);
} else {
System.out.println("'" + target + "' not found");
}
以上代码会输出Found 'world' at position 7
,因为子字符串"world"被找到了,它在原字符串中的起始位置是7。
注意:如果你不需要知道子字符串在原字符串中的位置,只需要判断是否包含子字符串,可以直接使用contains()
函数,如if (string.contains(target)) { ... }
。
3.获取指定索引位置的字符
在Java中,你可以使用字符串的charAt()
方法来获取指定索引位置的字符。
charAt()
方法接收一个整数作为参数,这个整数代表要获取的字符在字符串中的索引位置。索引位置从0开始计数,也就是说,字符串中第一个字符的索引位置为0,第二个字符的索引位置为1,以此类推。
如果要获取的索引位置超出了字符串的范围,charAt()
会抛出一个StringIndexOutOfBoundsException
异常。
下面是一个示例代码:
String str = "Hello, world!";
char c1 = str.charAt(0); // 获取字符串的第一个字符
char c2 = str.charAt(7); // 获取字符串中的第8个字符
char c3 = str.charAt(str.length() - 1); // 获取字符串的最后一个字符
char c4 = str.charAt(100); // 会抛出 StringIndexOutOfBoundsException 异常
System.out.println(c1); // 输出 'H'
System.out.println(c2); // 输出 'w'
System.out.println(c3); // 输出 '!'
需要注意的是,最后一个字符的索引位置是str.length() - 1
而不是str.length()
,因为索引位置是从0开始计数的。
字符串操作
1.获取子字符串
在Java中,你可以使用字符串的substring()
方法来获取子字符串。
substring()
方法接收两个整数作为参数,分别代表子字符串的起始索引位置和终止索引位置(不包括终止索引位置)。索引位置从0开始计数,也就是说,字符串中第一个字符的索引位置为0,第二个字符的索引位置为1,以此类推。
如果只传递了一个参数,那么方法会从该索引位置一直获取到字符串的末尾。
如果传递的起始索引位置大于等于字符串的长度,或者起始索引位置大于终止索引位置,substring()
会返回一个空字符串。
下面是一个示例代码:
String str = "Hello, world!";
String substr1 = str.substring(7); // 获取从索引位置7开始的子字符串
String substr2 = str.substring(0, 5); // 获取从索引位置0到5之间的子字符串,不包括5
System.out.println(substr1); // 输出 "world!"
System.out.println(substr2); // 输出 "Hello"
需要注意的是,substring()
方法返回的是一个新的字符串,而不是修改原有字符串。
2.去除空格
在Java中,你可以使用trim()方法去除字符串开头和结尾的空格。trim()方法不会改变原字符串,而是返回一个新字符串,因此你需要将返回的结果赋值给一个变量。
另外,如果你想要去除字符串中所有的空格(包括开头和结尾),可以使用replaceAll()方法来实现。replaceAll()方法接收两个参数,第一个参数是一个正则表达式,用于匹配要替换的字符,第二个参数是一个替换字符串,用于替换匹配的字符。在本例中,你可以使用正则表达式"\s+"来匹配一个或多个空格,并将其替换为空字符串""。
下面是一个示例代码:
String str = " Hello, world! ";
String trimmedStr = str.trim(); // 去除开头和结尾的空格
String noSpaceStr = str.replaceAll("\\s+", ""); // 去除所有空格
System.out.println(trimmedStr); // 输出 "Hello, world!"
System.out.println(noSpaceStr); // 输出 "Hello,world!"
需要注意的是,如果你只想去除字符串开头或结尾的空格,使用trim()方法即可。如果你想去除字符串中间的空格,可以使用replaceAll()方法,并传递适当的正则表达式作为第一个参数。
3.字符串替换
在Java中,你可以使用replaceAll()方法替换字符串中的字符。replaceAll()方法接收两个参数,第一个参数是一个正则表达式,用于匹配要替换的字符;第二个参数是要替换成的字符串。在本例中,你可以使用正则表达式""\s+""来匹配一个或多个空格,并将其替换为一个单独的空格。
下面是一个示例代码:
String str = "This is a test string.";
String replacedStr = str.replaceAll("is", "was");
System.out.println(replacedStr); // 输出 "Thwas was a test string."
String strWithSpaces = "This is a test string.";
String noExtraSpaces = strWithSpaces.replaceAll("\\s+", " ");
System.out.println(noExtraSpaces); // 输出 "This is a test string."
在这个例子中,第一个replaceAll()方法将字符串中的"is"替换为"was"。第二个replaceAll()方法将字符串中的多个空格替换为单个空格。
需要注意的是,正则表达式中的一些字符具有特殊含义,例如"|"和"."。如果你需要在替换中使用这些字符,需要使用反斜杠来进行转义。
4.判断字符串的开始与结尾
在Java中可以使用以下方法来判断字符串的开始与结尾:
- startsWith()方法:该方法接收一个字符串作为参数,如果此字符串以指定的前缀开头,则返回true;否则返回false。
String str = "Hello World";
if(str.startsWith("Hello")) {
System.out.println("字符串是以Hello开头的");
}
- endsWith()方法:该方法接收一个字符串作为参数,如果此字符串以指定的后缀结尾,则返回true;否则返回false。
String str = "Hello World";
if(str.endsWith("World")) {
System.out.println("字符串是以World结尾的");
}
需要注意的是,startsWith()和endsWith()方法都是区分大小写的。如果需要忽略大小写判断,可以先将字符串转换为小写或大写后再使用这两个方法。
String str = "Hello World";
if(str.toLowerCase().startsWith("hello")) {
System.out.println("字符串是以hello开头的");
}
if(str.toUpperCase().endsWith("WORLD")) {
System.out.println("字符串是以WORLD结尾的");
}
5.判断字符串是否相等
在Java中,判断字符串是否相等有以下三种方式:
- 使用equals()方法比较字符串是否相等。这是一种比较常用的方法,它比较两个字符串的内容是否相等,不考虑它们是否是同一个对象。
String str1 = "hello";
String str2 = "world";
if(str1.equals(str2)) {
System.out.println("两个字符串相等");
}
- 使用equalsIgnoreCase()方法比较字符串是否相等。该方法与equals()方法类似,但不考虑字符串的大小写。
String str1 = "HELLO";
String str2 = "hello";
if(str1.equalsIgnoreCase(str2)) {
System.out.println("两个字符串忽略大小写后相等");
}
- 使用==运算符比较两个字符串的地址是否相等。如果两个字符串是同一个对象,则它们的地址相等;反之,它们的地址不相等。
String str1 = "hello";
String str2 = new String("hello");
if(str1 == str2) {
System.out.println("两个字符串是同一个对象");
}
需要特别注意的是,当使用new关键字创建字符串对象时,会在堆内存中创建一个新的对象,即使两个字符串的内容相同,它们的地址也是不同的。因此,当要比较两个字符串的内容是否相等时,应该使用equals()或equalsIgnoreCase()方法。
6.按字典顺序比较字符串
在Java中,可以使用String类的compareTo()方法进行按字典顺序比较字符串。该方法返回一个整数值,表示当前字符串与参数字符串在字典顺序中的相对位置。如果当前字符串在字典顺序中排在参数字符串之前,则返回一个负整数;如果当前字符串在字典顺序中排在参数字符串之后,则返回一个正整数;如果两个字符串相等,则返回0。
示例代码:
String str1 = "abc";
String str2 = "bcd";
int result = str1.compareTo(str2);
if(result < 0) {
System.out.println(str1 + "在字典顺序中排在" + str2 + "之前");
} else if(result > 0) {
System.out.println(str1 + "在字典顺序中排在" + str2 + "之后");
} else {
System.out.println(str1 + "与" + str2 + "在字典顺序中相等");
}
输出结果:
abc在字典顺序中排在bcd之前
需要注意的是, compareTo()方法是区分大小写的,即大写字母排在小写字母之前。如果要忽略大小写进行比较,可以使用compareToIgnoreCase()方法。
7.字母大小写转化
在Java中,可以使用String类的toUpperCase()和toLowerCase()方法将字母转换为大写和小写。
toUpperCase()方法:
该方法将字符串中的所有字母转换为大写字母。示例代码:
String str = "hello world";
String upperCaseStr = str.toUpperCase();
System.out.println(upperCaseStr);
输出结果:
HELLO WORLD
toLowerCase()方法:
该方法将字符串中的所有字母转换为小写字母。示例代码:
String str = "Hello World";
String lowerCaseStr = str.toLowerCase();
System.out.println(lowerCaseStr);
输出结果:
hello world
需要注意的是,这些方法仅转换字母,不会对其它字符进行转换。
8.字符串分割
在Java中,可以使用String类的split()方法来对字符串进行分割。该方法接收一个正则表达式作为参数,将字符串按照该正则表达式进行分割,并返回分割后的字符串数组。
示例代码:
String str = "apple,banana,orange";
String[] strArray = str.split(",");
for(String s : strArray){
System.out.println(s);
}
输出结果:
apple
banana
orange
在上面的示例中,我们以逗号作为分隔符对字符串进行了分割,并将分割后的字符串保存到一个字符串数组strArray中。然后使用for循环遍历输出了每一个分割后的字符串。
需要注意的是,split()方法接收的参数是一个正则表达式,有些特殊字符需要进行转义,如“.”、“|”、“*”等。如果不进行转义,将会抛出异常。如下面的示例代码:
String str = "www.bai|du.com";
String[] strArray = str.split("|"); // 错误的分隔符
for(String s : strArray){
System.out.println(s);
}
代码中使用了“|”作为分隔符,但没有进行转义,导致程序抛出异常。正确的做法是将分隔符进行转义,如下所示:
String str = "www.bai|du.com";
String[] strArray = str.split("\\|"); // 正确的分隔符
for(String s : strArray){
System.out.println(s);
}
输出结果:
www.bai
du.com
格式化字符串
1.日期和时间字符串格式化
Java中可以使用SimpleDateFormat类来进行日期和时间的格式化操作。该类可以将日期和时间对象格式化为指定的字符串,也可以将字符串解析为日期和时间对象。
下面是一个示例代码,将日期格式化为指定的字符串:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println("当前日期时间:" + formattedDate);
}
}
输出结果:
当前日期时间:2022-03-06 15:25:13
在上述代码中,首先获取了当前的日期时间对象,然后创建了一个SimpleDateFormat对象,并指定了输出的日期时间格式为“yyyy-MM-dd HH:mm:ss”。最后调用SimpleDateFormat的format()方法将日期时间对象格式化为指定的字符串。
下面是几个常见的日期时间格式化的格式字符串:
格式字符 | 说明 |
---|---|
yyyy/MM/dd | 年/月/日 |
yyyy-MM-dd | 年-月-日 |
yyyy年MM月dd日 | 年月日 |
HH:mm:ss | 时:分:秒 |
HH:mm:ss.SSS | 时:分:秒.毫秒 |
yyyy-MM-dd HH:mm:ss | 年-月-日 时:分:秒 |
yyyyMMdd-HHmmss-SSS | 年月日-时分秒-毫秒 |
需要注意的是,SimpleDateFormat是非线程安全的类,不要将它定义成全局变量。在多线程环境下可以使用ThreadLocal来避免线程安全问题。
2.常规类型格式化
Java中常见的类型包括整数类型、浮点数类型、布尔类型和字符类型等。下面分别介绍它们的格式化方法。
整数类型格式化
Java中整数类型包括byte、short、int和long等。其中,byte和short类型可以用int类型来格式化,long类型则需要用专门的格式化方法。
格式化整数类型可以使用String类的format()方法或者System.out.printf()方法,它们的格式化参数语法类似于C语言的printf()函数。
下面是一个示例代码:
public class IntegerFormatExample {
public static void main(String[] args) {
byte b = 42;
short s = 1234;
int i = 123456;
long l = 1234567890L;
System.out.printf("byte: %d, short: %d, int: %d, long: %d\n", b, s, i, l);
System.out.printf("int: %d (hex: %x, octal: %o)\n", i, i, i);
System.out.printf("long: %d (hex: %x, octal: %o)\n", l, l, l);
}
}
输出结果:
byte: 42, short: 1234, int: 123456, long: 1234567890
int: 123456 (hex: 1e240, octal: 361100)
long: 1234567890 (hex: 499602d2, octal: 11145401322)
在上述代码中,使用了%d格式化整数类型。可以使用%x和%o格式化为十六进制和八进制数。
浮点数类型格式化
Java中浮点数类型包括float和double类型。格式化浮点数类型也可以使用String类的format()方法或者System.out.printf()方法。
下面是一个示例代码:
public class FloatFormatExample {
public static void main(String[] args) {
float f = 3.1415926f;
double d = 3.141592653589793;
System.out.printf("float: %f, %e\n", f, f);
System.out.printf("double: %f, %e\n", d, d);
System.out.printf("double: %.3f, %.3e\n", d, d);
}
}
输出结果:
float: 3.141593, 3.141593e+00
double: 3.141593, 3.141593e+00
double: 3.142, 3.142e+00
在上述代码中,使用了%f格式化浮点数类型。%e格式化为科学计数法,%.3f和%.3e表示保留3位小数。
布尔类型格式化
Java中布尔类型只有两个值,即true和false。格式化布尔类型可以使用条件表达式,也可以使用String类的format()方法或者System.out.printf()方法。
下面是一个示例代码:
public class BooleanFormatExample {
public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;
System.out.println(b1 ? "true" : "false");
System.out.println(b2 ? "true" : "false");
System.out.printf("%b, %b\n", b1, b2);
}
}
输出结果:
true
false
true, false
在上述代码中,使用了%b格式化布尔类型。
字符类型格式化
Java中字符类型为char,格式化字符类型可以使用String类的format()方法或者System.out.printf()方法。
下面是一个示例代码:
public class CharFormatExample {
public static void main(String[] args) {
char c1 = 'A';
char c2 = '\u0041';
System.out.printf("%c, %c\n", c1, c2);
}
}
输出结果:
A, A
在上述代码中,使用了%c格式化字符类型。
正则表达式
Java中的正则表达式可以用于字符串操作,例如匹配、查找、替换等。Java中正则表达式的处理依赖于Pattern和Matcher两个类。
Pattern类
Pattern类用于表示正则表达式。它提供了多种静态方法来创建Pattern对象,包括compile()、matches()、split()和replace()等。其中,compile()方法用于创建Pattern对象,其语法为:
public static Pattern compile(String regex)
该方法会根据指定的正则表达式创建一个Pattern对象。例如:
String regex = "\\d+";
Pattern pattern = Pattern.compile(regex);
上述代码中,指定了一个正则表达式"\d+",该正则表达式可以匹配一个或多个数字。然后使用Pattern类的compile方法创建了一个Pattern对象pattern。接下来,可以使用该对象进行匹配、查找、替换等操作。
Matcher类
Matcher类用于执行匹配操作。可以使用Pattern类的matcher()方法创建一个Matcher对象,其语法为:
public Matcher matcher(CharSequence input)
该方法会根据指定的字符序列创建一个Matcher对象。例如:
String input = "123-456-789";
Matcher matcher = pattern.matcher(input);
上述代码中,使用Pattern类的matcher()方法创建了一个Matcher对象matcher,该对象会根据Pattern对象pattern和输入字符串input来执行匹配操作。
Matcher类提供了多个方法来执行匹配操作,包括matches()、find()、group()和replaceAll()等。其中,matches()方法用于判断整个字符串是否匹配正则表达式,find()方法用于查找字符串中是否存在匹配的子串,group()方法用于返回当前匹配的子串,replaceAll()方法用于替换匹配的子串。例如:
while (matcher.find()) {
System.out.printf("match: [%s], start: %d, end: %d\n",
matcher.group(), matcher.start(), matcher.end());
}
String replaced = matcher.replaceAll("-");
System.out.println("replaced: " + replaced);
上述代码中,使用了Matcher类的find()和group()方法遍历了所有匹配的子串,并使用了replaceAll()方法将匹配的子串替换为"-"。
常用正则表达式语法
Java支持的正则表达式语法与其他语言类似,包括元字符、量词、字符组和反斜杠等。下面列出一些常用的正则表达式语法:
- 元字符:. 表示任意字符,^ 表示行的开头,$ 表示行的结尾,\ 转义字符。
- 量词:* 表示前一个字符出现0次或多次,+ 表示前一个字符出现1次或多次,? 表示前一个字符出现0次或1次,{n} 表示前一个字符出现n次,{n,} 表示前一个字符出现至少n次,{n,m} 表示前一个字符出现n到m次。
- 字符组:[] 表示字符组,可以匹配其中任意一个字符,如[A-Z]表示大写字母。
- 反斜杠:\d 表示数字,\w 表示单词字符(字母、数字和下划线),\s 表示空白字符(空格、制表符等),\b 表示单词边界,\n 表示换行符。
例如,使用正则表达式\d+可以匹配一个或多个数字。
字符串生成器
Java的字符串生成器(StringBuilder和StringBuffer)可以用于高效构建字符串,特别是当需要在循环中动态构建字符串时。
StringBuilder
StringBuilder类是Java中用于构建字符串的非线程安全类。它提供了多个方法用于添加和修改字符串,例如append()、insert()、delete()和replace()等。其中,append()方法用于添加字符串到末尾,insert()方法用于插入字符串到指定位置,delete()方法用于删除指定位置的字符,replace()方法用于替换指定范围内的字符。例如:
StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append(" ");
sb.append("world");
System.out.println(sb.toString());
上述代码中,使用了StringBuilder类的append()方法将字符串"hello"和"world"添加到字符串生成器中,并使用toString()方法将其转换为字符串输出。
StringBuffer
StringBuffer类与StringBuilder类类似,也用于构建字符串,但它是线程安全的。它提供了与StringBuilder类相同的方法,包括append()、insert()、delete()和replace()等。例如:
StringBuffer sb = new StringBuffer();
sb.append("hello");
sb.append(" ");
sb.append("world");
System.out.println(sb.toString());
上述代码中,使用了StringBuffer类的append()方法将字符串"hello"和"world"添加到字符串生成器中,并使用toString()方法将其转换为字符串输出。
在使用字符串生成器时,推荐使用StringBuilder类,除非需要在多线程环境中操作字符串时才使用StringBuffer类。