Java字符串处理:按标点分割数组并实现大小写格式转换
解决方案:分步处理字符串需求
没问题,我来帮你一步步实现这个字符串处理的需求,针对你给出的原字符串:
String one = "ATrueRebelYouAre!EveryoneWasImpressed.You'llDoWellToContinueInTheSameSpirit?";
我们需要完成三个核心步骤:按指定符号分割字符串、在大写字符前加空格、转小写,下面是具体实现和解释:
步骤拆解与代码实现
方法1:传统循环方式
public class StringProcessor { public static void main(String[] args) { String one = "ATrueRebelYouAre!EveryoneWasImpressed.You'llDoWellToContinueInTheSameSpirit?"; // 1. 按!、?、.分割字符串,得到初始数组 String[] splitParts = one.split("[!?.]"); // 2. 遍历处理每个分割后的字符串 for (int i = 0; i < splitParts.length; i++) { String current = splitParts[i]; // 跳过分割产生的空字符串(比如原字符串结尾的?会生成空元素) if (!current.isEmpty()) { // 在每个大写字母前添加空格 → 转小写 → 去除前导空格 String processed = current.replaceAll("([A-Z])", " $1") .toLowerCase() .trim(); splitParts[i] = processed; } } // 输出处理后的结果 for (String part : splitParts) { if (!part.isEmpty()) { System.out.println(part); } } } }
方法2:Stream流简化方式(Java 8+)
如果偏好更简洁的写法,可以用Stream流来处理:
import java.util.Arrays; public class StringProcessor { public static void main(String[] args) { String one = "ATrueRebelYouAre!EveryoneWasImpressed.You'llDoWellToContinueInTheSameSpirit?"; Arrays.stream(one.split("[!?.]")) // 过滤分割产生的空字符串 .filter(part -> !part.isEmpty()) // 对每个字符串执行:大写前加空格 → 转小写 → 去前导空格 .map(part -> part.replaceAll("([A-Z])", " $1").toLowerCase().trim()) // 逐个输出结果 .forEach(System.out::println); } }
关键部分解释
- 字符串分割:
split("[!?.]")使用正则字符类,匹配!、?、.这三个分隔符,将原字符串拆分为数组。注意原字符串结尾的?会生成一个空元素,所以需要后续过滤。 - 大写前加空格:
replaceAll("([A-Z])", " $1")通过正则捕获每个大写字母,在其前面插入空格。比如ATrue会变成A true。 - 转小写与去空格:
toLowerCase()把所有字符转为小写,trim()去除开头的多余空格(因为第一个字符是大写,替换后会产生前导空格)。
输出结果
运行代码后会得到以下结果:
a true rebel you are everyone was impressed you'll do well to continue in the same spirit
内容的提问来源于stack exchange,提问作者Tigran




