Java函数用于查找和替换字符串中指定的字符
发布时间:2023-06-30 19:05:40
Java中有很多函数可以用于查找和替换字符串中指定的字符,下面介绍一些常用的函数及其用法:
1. indexOf()函数:该函数用于查找字符串中 次出现指定字符的位置。如果找到了该字符,则返回其索引值;如果没找到,则返回-1。例如:
String str = "hello world!";
int index = str.indexOf('o');
System.out.println("字符'o'在字符串中的索引位置为:" + index);
输出结果为:4
2. lastIndexOf()函数:该函数用于查找字符串中最后一次出现指定字符的位置。如果找到了该字符,则返回其索引值;如果没找到,则返回-1。例如:
String str = "hello world!";
int index = str.lastIndexOf('o');
System.out.println("字符'o'在字符串中最后一次出现的索引位置为:" + index);
输出结果为:7
3. replace()函数:该函数用于将字符串中所有指定字符替换为新的字符。例如:
String str = "hello world!";
String newStr = str.replace('o', 'e');
System.out.println("将字符串中的字符'o'替换为'e'后的字符串为:" + newStr);
输出结果为:helle werld!
4. replaceFirst()函数:该函数用于将字符串中 次出现的指定字符替换为新的字符。例如:
String str = "hello world!";
String newStr = str.replaceFirst("o", "e");
System.out.println("将字符串中 次出现的字符'o'替换为'e'后的字符串为:" + newStr);
输出结果为:helle world!
5. split()函数:该函数用于将字符串按照指定字符分割成字符串数组。例如:
String str = "hello,world!";
String[] arr = str.split(",");
System.out.println("按照','分割后的字符串数组为:" + Arrays.toString(arr));
输出结果为:[hello, world!]
6. substring()函数:该函数用于截取字符串的子串,可以从指定位置开始截取到指定位置结束。例如:
String str = "hello world!";
String subStr = str.substring(6, 11);
System.out.println("从索引位置6开始截取到索引位置11结束的子串为:" + subStr);
输出结果为:world!
总结:以上是Java中常用的用于查找和替换字符串中指定的字符的函数,通过这些函数可以方便地对字符串进行操作。注意,Java中的字符串是不可变的,所以上述函数的返回值都是新的字符串,原字符串不会改变。如果对字符串进行频繁的操作,建议使用StringBuilder或StringBuffer类,它们是可变的字符串类,性能更好。
