java如何去掉字符串首尾的双引号?
2025-01-29
有时候在处理如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() 方法则更加简洁高效。