Java如何获取字符串中最后两个分号之后的内容
Java提取字符串最后两个分号后内容的实现方法
首先明确需求:提取给定字符串中倒数第二个分号之后的全部内容,示例输入Mobiles;Students;Test;Yes;1234,预期输出为Yes;1234。
下面提供两种常用实现方案:
方案1:通过lastIndexOf定位截取(推荐,性能更高)
不需要拆分整个字符串,直接定位分号位置截取,适合长字符串、高并发场景使用:
public class SemicolonExtractDemo { public static String extractAfterLastTwoSemicolons(String input) { // 空输入直接返回 if (input == null || input.isEmpty()) { return input; } // 定位最后一个分号位置 int lastSemicolonIndex = input.lastIndexOf(';'); if (lastSemicolonIndex == -1) { // 字符串中没有分号,返回原串 return input; } // 定位倒数第二个分号位置,从最后一个分号的前一位开始向前搜索 int secondLastSemicolonIndex = input.lastIndexOf(';', lastSemicolonIndex - 1); if (secondLastSemicolonIndex == -1) { // 字符串中只有1个分号,可根据业务需求调整返回逻辑,这里默认返回最后一个分号后的内容 return input.substring(lastSemicolonIndex + 1); } // 截取倒数第二个分号之后的全部内容,+1是跳过分号本身 return input.substring(secondLastSemicolonIndex + 1); } public static void main(String[] args) { String testStr = "Mobiles;Students;Test;Yes;1234"; System.out.println(extractAfterLastTwoSemicolons(testStr)); // 输出结果:Yes;1234 } }
方案2:通过split拆分拼接(代码更简洁)
拆分字符串为数组后取最后两个元素拼接,代码易读性更高,适合短字符串场景:
public static String extractBySplit(String input) { if (input == null || input.isEmpty()) { return input; } String[] splitParts = input.split(";"); // 分号数量不足2个时直接返回原串,可按需调整逻辑 if (splitParts.length <= 2) { return input; } // 拼接最后两个元素 return splitParts[splitParts.length - 2] + ";" + splitParts[splitParts.length - 1]; }
注意:如果业务要求分号数量不足2个时抛出异常,可自行修改边界判断逻辑
内容的提问来源于stack exchange,提问作者Vijay Pathipaka
相关产品推荐
相关产品推荐

