Java中字符串搜索与替换函数梳理
在Java中,字符串搜索和替换是一项常见的操作。Java提供了一系列的字符串搜索和替换函数,可以根据不同的需求选择合适的函数来完成相关操作。本文将对Java中常用的字符串搜索和替换函数进行梳理。
1. 字符串搜索函数:
1.1. indexOf:该函数用于搜索字符串中 次出现指定字符或子字符串的位置。函数的定义如下:
int indexOf(int ch) int indexOf(int ch, int fromIndex) int indexOf(String str) int indexOf(String str, int fromIndex)
其中,ch为要搜索的字符的Unicode代码,fromIndex为搜索的起始位置,str为要搜索的子字符串。
示例使用:
String str = "hello world";
int index1 = str.indexOf('o'); // 返回值为4
int index2 = str.indexOf("world"); // 返回值为6
1.2. lastIndexOf:该函数用于搜索字符串中最后一次出现指定字符或子字符串的位置。函数的定义和用法与indexOf相似。
示例使用:
String str = "hello world";
int index = str.lastIndexOf('o'); // 返回值为7
1.3. contains:该函数用于判断字符串是否包含指定的字符或子字符串。函数的定义如下:
boolean contains(CharSequence sequence)
示例使用:
String str = "hello world";
boolean result = str.contains("wor"); // 返回值为true
2. 字符串替换函数:
2.1. replace:该函数用于将字符串中的指定字符或子字符串替换为新的字符或子字符串。函数的定义如下:
String replace(CharSequence target, CharSequence replacement)
其中,target为被替换的字符或子字符串,replacement为替换后的字符或子字符串。
示例使用:
String str = "hello world";
String newStr = str.replace("world", "Java"); // 返回值为"hello Java"
2.2. replaceFirst:该函数用于将字符串中 次出现的指定字符或子字符串替换为新的字符或子字符串,函数的定义如下:
String replaceFirst(String regex, String replacement)
其中,regex为要替换的字符或子字符串的正则表达式,replacement为替换后的字符或子字符串。
示例使用:
String str = "hello world";
String newStr = str.replaceFirst("o", "O"); // 返回值为"hellO world"
2.3. replaceAll:该函数用于将字符串中所有匹配指定字符或子字符串的部分替换为新的字符或子字符串。函数的定义如下:
String replaceAll(String regex, String replacement)
其中,regex为要替换的字符或子字符串的正则表达式,replacement为替换后的字符或子字符串。
示例使用:
String str = "hello world";
String newStr = str.replaceAll("o", "O"); // 返回值为"hellO wOrld"
3. 总结与注意事项:
在使用字符串的搜索和替换函数时,需要注意一些细节:
- indexOf和lastIndexOf函数返回的是匹配字符或子字符串的位置,如果没有找到,则返回-1;
- contains函数返回的是一个布尔值,表示字符串是否包含目标字符或子字符串;
- replace、replaceFirst和replaceAll函数返回的是替换后的新字符串,原字符串不会改变;
- replaceFirst和replaceAll函数中的regex参数为正则表达式,可以用来匹配更复杂的模式。
以上是Java中常用的字符串搜索和替换函数的梳理,根据不同的需求,可以选择合适的函数来完成相应的操作。
