欢迎访问宙启技术站
智能推送

Java中常用的字符串处理函数及示例代码

发布时间:2023-06-20 14:14:26

Java是一种十分常用的编程语言,它的字符串处理函数也非常丰富。下面就来介绍一些比较常用的字符串处理函数及示例代码:

1. String类下的charAt(int index)函数:返回指定索引处的字符。实例如下:

String s = "hello";
char c = s.charAt(1);
System.out.println(c);  // 'e'

2. String类下的concat(String str)函数:将指定字符串连接到此字符串的末尾。实例如下:

String s = "hello";
s = s.concat(" world");
System.out.println(s);  // "hello world"

3. String类下的contains(CharSequence s)函数:判断此字符串中是否包含指定的字符序列。实例如下:

String s = "hello world";
boolean b = s.contains("world");
System.out.println(b);  // true

4. String类下的equals(Object anObject)函数:比较此字符串与指定对象是否相等。实例如下:

String s1 = "hello";
String s2 = "world";
boolean b1 = s1.equals(s2);
boolean b2 = s1.equals("hello");
System.out.println(b1);  // false
System.out.println(b2);  // true

5. String类下的equalsIgnoreCase(String anotherString)函数:将此字符串与指定的字符串进行比较,忽略大小写。实例如下:

String s1 = "Hello";
String s2 = "hello";
boolean b = s1.equalsIgnoreCase(s2);
System.out.println(b);  // true

6. String类下的indexOf(String str)函数:返回指定子字符串在此字符串中 次出现处的索引。实例如下:

String s = "hello world";
int i = s.indexOf("o");
System.out.println(i);  // 4

7. String类下的lastIndexOf(String str)函数:返回指定子字符串在此字符串中最后一次出现处的索引。实例如下:

String s = "hello world";
int i = s.lastIndexOf("o");
System.out.println(i);  // 7

8. String类下的replace(char oldChar, char newChar)函数:返回一个新字符串,它是此字符串的一个副本,其中所有出现的旧字符都被新字符替换。实例如下:

String s = "hello world";
s = s.replace("l", "z");
System.out.println(s);  // "hezzo worzd"

9. String类下的split(String regex)函数:根据匹配给定的正则表达式来拆分此字符串。实例如下:

String s = "hello world";
String[] arr = s.split(" ");
System.out.println(Arrays.toString(arr));  // ["hello", "world"]

10. String类下的substring(int beginIndex, int endIndex)函数:返回一个新字符串,它是此字符串的一个子字符串。实例如下:

String s = "hello world";
String s1 = s.substring(2);
String s2 = s.substring(2, 7);
System.out.println(s1);  // "llo world"
System.out.println(s2);  // "llo w"

11. String类下的toLowerCase()函数:使用默认语言环境的规则将此字符串转换为小写。实例如下:

String s = "HeLLo WoRLD";
s = s.toLowerCase();
System.out.println(s);  // "hello world"

12. String类下的toUpperCase()函数:使用默认语言环境的规则将此字符串转换为大写。实例如下:

String s = "hello world";
s = s.toUpperCase();
System.out.println(s);  // "HELLO WORLD"

13. StringBuffer类下的append(String str)函数:将指定字符串追加到此字符序列。实例如下:

StringBuffer sb = new StringBuffer("hello");
sb.append(" world");
System.out.println(sb.toString());  // "hello world"

14. StringBuffer类下的reverse()函数:将此字符序列用其反转形式取代。实例如下:

StringBuffer sb = new StringBuffer("hello");
sb.reverse();
System.out.println(sb.toString());  // "olleh"

以上仅是Java字符串处理函数中常用的一部分,还有很多其他函数值得探索和学习。通过多写代码并参考Java官方文档,可以逐步掌握它们的使用。