java如何去掉字符串首尾的双引号?

有时候在处理如csv等数据的时候,需要用到这个算法。

在 Java 中,可以使用 String 类提供的 replaceAll() 方法或 substring() 方法来去除字符串首尾的引号(")。

方法 1:使用 replaceAll() 方法去除首尾的引号

可以使用正则表达式匹配字符串的首尾引号,并将其替换为空字符串。

java

public class Main {
    public static void main(String[] args) {
        String str = "\"Hello, World!\"";
        // 去除首尾的引号String result = str.replaceAll("^\"|\"$", "");
        System.out.println(result);  // 输出: Hello, World!
    }
}
  • ^":匹配字符串开头的引号。
  • \"$:匹配字符串末尾的引号。
  • |:表示“或”操作,匹配首尾的引号。

方法 2:使用 substring() 方法

可以检查字符串的第一个和最后一个字符是否是引号,然后使用 substring() 方法去除。

java

public class Main {
    public static void main(String[] args) {
        String str = "\"Hello, World!\"";
        // 检查首尾是否是引号if (str.startsWith("\"") && str.endsWith("\"")) {
            str = str.substring(1, str.length() - 1);
        }
        System.out.println(str);  // 输出: Hello, World!
    }
}
  • startsWith("\""):检查字符串是否以引号开头。
  • endsWith("\""):检查字符串是否以引号结尾。
  • substring(1, str.length() - 1):返回去除首尾字符后的子字符串。

总结

  • 如果只需处理首尾的引号,可以使用 replaceAll() 方法来一次性处理。
  • 如果只在字符串的第一个和最后一个字符是引号时进行处理,substring() 方法则更加简洁高效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值