要删除字符串中第三个和最后一个出现的',可以使用以下代码:

public class Main {
    public static void main(String[] args) {
        String str = "Hello 'World', 'Hello' World";
        System.out.println("原始字符串:" + str);
        
        int thirdQuoteIndex = str.indexOf("'", str.indexOf("'") + 1); // 获取第三个'的索引
        int lastQuoteIndex = str.lastIndexOf("'"); // 获取最后一个'的索引
        
        if (thirdQuoteIndex != -1 && lastQuoteIndex != -1) {
            StringBuilder stringBuilder = new StringBuilder(str);
            stringBuilder.deleteCharAt(thirdQuoteIndex);
            stringBuilder.deleteCharAt(lastQuoteIndex - 1); // 删除最后一个'之前的空格
            
            str = stringBuilder.toString();
        }
        
        System.out.println("删除第三个和最后一个'后的字符串:" + str);
    }
}

输出结果:

原始字符串:Hello 'World', 'Hello' World
删除第三个和最后一个'后的字符串:Hello 'World' Hello World

这段代码首先找到字符串中第一个'的索引,然后使用indexOf()方法再找到第二个'的索引,从而获取到第三个'的索引。然后使用lastIndexOf()方法找到最后一个'的索引。

然后使用StringBuilder类来操作字符串,先删除第三个',再删除最后一个'之前的空格。

最后将StringBuilder转换为字符串,并输出结果。

请注意,如果字符串中没有第三个或最后一个',则不会进行删除操作。

Java 字符串删除第三个和最后一个双引号

原文地址: https://www.cveoy.top/t/topic/pgER 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录