编辑
2024-05-10
Java
00
请注意,本文编写于 365 天前,最后修改于 364 天前,其中某些信息可能已经过时。

目录

分割字符串
匹配字符串
组合字符串
替换字符串
转换大小写
去除空白
比较字符串
搜索子字符串
提取子字符串
字符串与字节数组转换
其他常用方法

算法题常遇到一些字符串操作,记住这些API就能更快码出来,以下是一些常用的字符串处理函数:

分割字符串

  • split(String regex): 使用正则表达式作为分隔符来分割字符串。
  • split(String regex, int limit): 与split(String regex)类似,但限制了分割后的数组大小。

匹配字符串

  • matches(String regex): 判断字符串是否匹配给定的正则表达式。
  • contains(CharSequence s): 判断字符串是否包含指定的子字符串。

组合字符串

  • concat(String str): 将指定字符串连接到当前字符串的末尾。
  • join(CharSequence delimiter, CharSequence... elements): 使用指定的分隔符连接一系列元素。

替换字符串

  • replace(CharSequence target, CharSequence replacement): 将字符串中所有出现的指定字符序列替换为另一个字符序列。
  • replaceAll(String regex, String replacement): 使用正则表达式替换所有匹配的子字符串。

转换大小写

  • toLowerCase(): 将字符串中的所有字符都转换为小写。
  • toUpperCase(): 将字符串中的所有字符都转换为大写。

去除空白

  • trim(): 去除字符串两端的空白字符。
  • strip(): Java 11新增的方法,去除字符串两端的空白字符。

比较字符串

  • equals(Object anotherObject): 比较当前字符串与另一个对象是否相等。
  • equalsIgnoreCase(String anotherString): 与equals(Object anotherObject)类似,但忽略大小写。

搜索子字符串

  • indexOf(String str): 返回指定子字符串在此字符串中第一次出现处的索引。
  • lastIndexOf(String str): 返回指定子字符串在此字符串中最后一次出现处的索引。

提取子字符串

  • substring(int beginIndex): 返回一个新的字符串,它是此字符串的一个子字符串。
  • substring(int beginIndex, int endIndex): 返回一个新的字符串,它是此字符串的一个子字符串。

字符串与字节数组转换

  • getBytes(): 将字符串转换为字节数组。
  • new String(byte[] bytes, int offset, int length): 使用指定的字节数组构造一个新的字符串。

其他常用方法

  • length(): 返回字符串的长度。
  • isEmpty(): 判断字符串是否为空。
  • charAt(int index): 返回指定索引处的字符。
  • contains(CharSequence s): 判断字符串是否包含指定的子字符串。

以下是代码示例:

java
public class StringExample { public static void main(String[] args) { String str = "Hello, World!"; // 分割字符串 String[] parts = str.split(", "); System.out.println("分割字符串: " + String.join(" ", parts)); // 匹配字符串 boolean matches = str.matches(".*World.*"); System.out.println("匹配字符串: " + matches); // 组合字符串 String combined = str.concat(" How are you?"); System.out.println("组合字符串: " + combined); // 替换字符串 String replaced = str.replace("World", "Java"); System.out.println("替换字符串: " + replaced); // 转换大小写 String lower = str.toLowerCase(); String upper = str.toUpperCase(); System.out.println("转换大小写: " + lower + " | " + upper); // 去除空白 String trimmed = str.trim(); System.out.println("去除空白: " + trimmed); // 比较字符串 boolean equals = str.equals("Hello, World!"); boolean equalsIgnoreCase = str.equalsIgnoreCase("hello, world!"); System.out.println("比较字符串: " + equals + " | " + equalsIgnoreCase); // 搜索子字符串 int index = str.indexOf("World"); System.out.println("搜索子字符串: " + index); // 提取子字符串 String subStr = str.substring(7, 12); System.out.println("提取子字符串: " + subStr); // 字符串与字节数组转换 byte[] bytes = str.getBytes(); String fromBytes = new String(bytes); System.out.println("字符串与字节数组转换: " + fromBytes); } }

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!