Java -- 字符串处理

1  创建字符串

1.1  直接赋值

String str1 = "Hello, World!";

1.2  使用构造函数

String str2 = new String("Hello, World!");

1.3  字符数组转字符串

char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str3 = new String(chars);

2  字符串的常用操作

2.1  获取字符串长度

int length = str1.length();

2.2  获取字符串中的字符

char ch = str1.charAt(0);  // 获取字符串的第一个字符

2.3  字符串比较

boolean isEqual = str1.equals("Hello, World!");
boolean isIgnoreCaseEqual = str1.equalsIgnoreCase("hello, world!");

//equals(Object anObject) 方法比较两个字符串的内容是否相等。
//equalsIgnoreCase(String anotherString) 方法忽略大小写比较字符串。

2.4   字符串查找

int index = str1.indexOf("World");  // 查找子字符串首次出现的位置
int lastIndex = str1.lastIndexOf("o");  // 查找子字符串最后一次出现的位置

2.5  提取子字符串

String subStr = str1.substring(7);  // 从索引7开始提取子字符串
String subStr2 = str1.substring(7, 12);  // 提取索引7到12之间的子字符串

3  字符串的拼接与连接

3.1  使用 + 操作符

String greeting = "Hello, " + "World!";

3.2  使用 concat() 方法

String str4 = "Hello".concat(", World!");

3.3  使用 StringBuilderStringBuffer

StringBuilder sb = new StringBuilder();
sb.append("Hello, ");
sb.append("World!");
String result = sb.toString();

4  字符串替换

4.1  替换字符

String replaced = str1.replace('o', 'a');  // 替换所有 'o' 为 'a'

4.2  替换子字符串

String replacedStr = str1.replace("World", "Java");

4.3  使用正则表达式替换

String replacedAll = str1.replaceAll("\\d", "X");  // 将所有数字替换为 'X'

5   字符串拆分

5.1  使用 split() 方法

String[] words = str1.split(" ");  // 按空格拆分字符串

6  字符串格式化

6.1  使用 String.format()

String formatted = String.format("Hello, %s! You have %d new messages.", "Alice", 5);

7  字符串检查

7.1  检查字符串是否以特定前缀开头:startsWith

boolean starts = str1.startsWith("Hello");

7.2  检查字符串是否以特定后缀结尾:endsWith

boolean ends = str1.endsWith("World!");

7.3  检查字符串是否包含特定子字符串:contains

boolean contains = str1.contains("World");

8  字符串的不可变性

8.1  不可变性概念

String str5 = "Hello";
str5 = str5.concat(", World!");  // 生成了新的字符串对象,原来的字符串对象未改变

8.2  使用 StringBuilder 处理可变字符串

StringBuilder sb = new StringBuilder("Hello");
sb.append(", World!");  // 对于大量字符串操作,使用 StringBuilder 可以提高性能

9  正则表达式与字符串处理

9.1  使用 matches() 方法

boolean isMatch = str1.matches("Hello,\\s\\w+!");

9.2  使用 split() 与正则表达式

String[] parts = "one,two,three".split(",");

9.3  使用 PatternMatcher

import java.util.regex.*;

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("abc123xyz");

while (matcher.find()) {
    System.out.println(matcher.group());
}

10  字符串与基本类型的转换

10.1  字符串转基本类型

int num = Integer.parseInt("123");
double d = Double.parseDouble("3.14");

10.2  基本类型转字符串

String s = String.valueOf(123);

11  字符串与字符数组的转换

11.1  字符串转字符数组

char[] chars = str1.toCharArray();

11.2  字符数组转字符串

String str6 = new String(chars);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颜回.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值