本文共 7259 字,大约阅读时间需要 24 分钟。
Java 字符串操作小技巧:12 个实用方法
作为一名开发者,字符串在我们的日常工作中无处不在。它是 Java 中最具代表性的类之一,就像李佳琪、李诞那样具有“大哥”地位。然而,面试官往往会用一些看似简单却考验技术底部的字符串操作来测试我们。为了让你在面试中脱颖而出,我整理了12个实用的Java字符串操作技巧。下面一起来看看这些技巧吧!
01、如何获取字符串中的不同字符及其数量?
解决方案:
我们可以通过遍历字符串中的每个字符,并将其存储在一个Map中。Map的特点是键不允许重复,这样就能自动统计每个字符的出现次数。
实现代码:
public class DistinctCharsCount { public static void main(String[] args) { printDistinctCharsWithCount("itwanger"); printDistinctCharsWithCount("chenmowanger"); } private static void printDistinctCharsWithCount(String input) { Map charsWithCountMap = new LinkedHashMap<>(); for (char c : input.toCharArray()) { Integer oldValue = charsWithCountMap.get(c); int newValue = oldValue != null ? oldValue + 1 : 1; charsWithCountMap.put(c, newValue); } System.out.println("字符及数量:" + charsWithCountMap); }} 代码解释:
- 使用
LinkedHashMap保持字符的顺序,方便查看。 - 遍历字符串中的每个字符,检查是否已经存在于
Map中,不存在则添加新记录,存在则更新计数。 - 最后输出
Map中的结果,方便查看每个字符的数量。
02、如何反转字符串?
解决方案:
可以使用StringBuilder或StringBuffer来实现字符串的反转操作。StringBuilder和StringBuffer的区别在于同步性,前者性能更高。
实现代码:
public class ReverseAString { public static void main(String[] args) { reverseInputString("沉默王二"); } private static void reverseInputString(String input) { StringBuilder sb = new StringBuilder(input); String result = sb.reverse().toString(); System.out.println("反转后的字符串:" + result); }} 代码解释:
- 使用
StringBuilder创建一个字符串对象副本。 - 调用
reverse()方法反转字符串。 - 将反转后的字符串转换为
String并输出。
03、如何判断字符串是否为回文?
解决方案:
回文字符串是指正读和反读都一样的字符串。可以通过遍历字符串的前半部分,与后半部分对照来判断。
实现代码:
public class PalindromeString { public static void main(String[] args) { checkPalindromeString("沉默王二"); checkPalindromeString("沉默王二 二王默沉"); } private static void checkPalindromeString(String input) { boolean result = true; int length = input.length(); for (int i = 0; i < length / 2; i++) { if (input.charAt(i) != input.charAt(length - i - 1)) { result = false; break; } } System.out.println(input + " 对称吗? " + result); }} 代码解释:
- 遍历字符串的前半部分。
- 比较每个字符与其对称位置的字符。
- 如果有任何一个字符不匹配,设置为
false并退出循环。
04、如何删除字符串中的指定字符?
解决方案:
可以使用String.replaceAll()方法,通过正则表达式替换指定字符为空字符串。
实现代码:
public class RemoveCharFromString { public static void main(String[] args) { removeCharFromString("沉默王二", '二'); removeCharFromString("chenmowanger", 'n'); } private static void removeCharFromString(String input, char c) { String result = input.replaceAll(String.valueOf(c), ""); System.out.println("删除后的字符串:" + result); }} 代码解释:
- 使用
replaceAll()方法将指定字符替换为空字符串。 String.valueOf(c)将字符转换为字符串形式,以适应replaceAll()的参数类型。
05、如何证明字符串是不可变的?
解决方案:
通过赋值操作符=观察字符串是否会变化。由于字符串是不可变的,赋值操作不会改变其原有对象。
实现代码:
public class StringImmutabilityTest { public static void main(String[] args) { String s1 = "沉默王二"; String s2 = s1; System.out.println(s1 == s2); // true s1 = "沉默王三"; System.out.println(s1 == s2); // false System.out.println(s2); // 沉默王二 }} 代码解释:
s1和s2最初指向同一个字符串对象。- 修改
s1后,指向新的字符串对象。 - 最终输出显示
s2仍为原始字符串,证明字符串不可变。
06、如何统计字符串中的单词数?
解决方案:
使用split()方法对字符串进行拆分,拆分规则是任意数量的空白字符,然后计算拆分后的数组长度。
实现代码:
public class CountNumberOfWordsInString { public static void main(String[] args) { countNumberOfWords("My name is Wanger"); countNumberOfWords("I Love Java Programming"); countNumberOfWords(" Java is very important "); } private static void countNumberOfWords(String line) { String trimmedLine = line.trim(); int count = trimmedLine.isEmpty() ? 0 : trimmedLine.split("\\s+").length; System.out.println("单词数:" + count); }} 代码解释:
- 使用
trim()去除首尾空白字符。 - 使用
split("\\s+")拆分字符串,\\s+表示任意数量的空白字符。 - 计算拆分后的数组长度即为单词数。
07、如何检查两个字符串中的字符是否完全相同?
解决方案:
将两个字符串转换为字符集合,比较两个集合是否相等。
实现代码:
public class CheckSameCharsInString { public static void main(String[] args) { sameCharsStrings("沉默王二", "沉王二默"); sameCharsStrings("沉默王二", "沉默王三"); } private static void sameCharsStrings(String s1, String s2) { Set set1 = s1.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); System.out.println("set1:" + set1); Set set2 = s2.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); System.out.println("set2:" + set2); System.out.println("是否相同:" + set1.equals(set2)); }} 代码解释:
- 使用
chars().mapToObj()将字符串转换为字符流,并收集到集合中。 - 比较两个集合是否相等,返回布尔值。
08、如何判断一个字符串是否包含另一个字符串?
解决方案:
使用contains()方法直接判断字符串是否包含指定子字符串。
实现代码:
public class StringContainsSubstring { public static void main(String[] args) { String s1 = "沉默王二"; String s2 = "沉默"; System.out.println(s1.contains(s2)); // true }} 代码解释:
contains()方法内部使用indexOf()检查子字符串的位置。- 返回值
>= 0表示包含,-1表示不包含。
09、如何交换两个字符串而不使用第三个变量?
解决方案:
可以通过拼接和子字符串操作来实现交换。具体步骤如下:
实现代码:
public class SwapTwoStrings { public static void main(String[] args) { String s1 = "沉默"; String s2 = "王二"; s1 = s1.concat(s2); // 拼接后的字符串为 "沉默王二" s2 = s1.substring(0, s1.length() - s2.length()); // 提取前半部分,"沉默" s1 = s1.substring(s2.length()); // 提取后半部分,"王二" System.out.println(s1); // 王二 System.out.println(s2); // 沉默 }} 代码解释:
- 拼接两个字符串,生成新字符串。
- 使用
substring()方法分别提取两个字符串。
10、如何找出字符串中的第一个不重复字符?
解决方案:
遍历字符串,记录已出现的字符。如果发现一个字符没有被记录,立即返回它。
实现代码:
public class FindNonRepeatingChar { public static void main(String[] args) { System.out.println(printFirstNonRepeatingChar("沉默王沉沉默二")); System.out.println(printFirstNonRepeatingChar("沉默王沉")); System.out.println(printFirstNonRepeatingChar("沉沉沉")); } private static Character printFirstNonRepeatingChar(String string) { char[] chars = string.toCharArray(); List discardedChars = new ArrayList<>(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (discardedChars.contains(c)) { continue; } for (int j = i + 1; j < chars.length; j++) { if (c == chars[j]) { discardedChars.add(c); break; } else if (j == chars.length - 1) { return c; } } } return null; }} 代码解释:
- 遍历每个字符,检查是否已被记录到
List中。 - 如果找到一个未重复字符,立即返回它。
11、如何检查字符串中只包含数字?
解决方案:
使用正则表达式匹配字符串,判断是否全是数字。
实现代码:
public class CheckIfStringContainsDigitsOnly { public static void main(String[] args) { digitsOnlyString("123 沉默王二"); digitsOnlyString("123"); } private static void digitsOnlyString(String string) { if (string.matches("\\d+")) { System.out.println("只包含数字的字符串:" + string); } }} 代码解释:
matches("\\d+")匹配一串由数字组成的字符串。
12、如何实现字符串的深度拷贝?
解决方案:
由于字符串是不可变的,可以直接使用赋值操作符=来实现拷贝。
实现代码:
public class JavaStringCopy { public static void main(String args[]) { String str = "沉默王二"; String strCopy = str; // 深度拷贝,字符串不可变 str = "沉默王三"; System.out.println(strCopy); // 沉默王二 }} 代码解释:
strCopy和str指向同一个字符串对象。- 修改
str后,strCopy仍保持原值。
总结
这些技巧涵盖了Java字符串操作的核心内容,既有简单的反转、判断回文,又有复杂的字符统计和深度拷贝。希望这些方法能帮助你在面试中脱颖而出,同时也能提升你对字符串操作的理解。
发表评论
最新留言
关于作者