Java中的String类方法的基本用法
发布时间:2023-06-23 06:41:32
Java中在字符串类String中有很多有用的方法,可以方便的处理字符串。以下是Java中String类方法的基本用法。
1. charAt(int index)
返回给定索引处的字符。索引从零开始。
例如:
String str = "hello"; char ch = str.charAt(1); System.out.println(ch); // 输出e
2. length()
返回字符串的长度。
例如:
String str = "hello"; int len = str.length(); System.out.println(len); // 输出5
3. substring(int beginIndex, int endIndex)
返回一个子字符串,该子字符串以指定的开始索引和结束索引之间的字符组成。
例如:
String str = "hello"; String sub = str.substring(1, 4); System.out.println(sub); // 输出ell
4. indexOf(char ch)
返回字符在字符串中 次出现的索引。
例如:
String str = "hello";
int index = str.indexOf('l');
System.out.println(index); // 输出2
5. lastIndexOf(char ch)
返回字符在字符串中最后一次出现的索引。
例如:
String str = "hello";
int index = str.lastIndexOf('l');
System.out.println(index); // 输出3
6. equals(Object obj)
将此字符串与另一个对象比较。
例如:
String str1 = "hello";
String str2 = "world";
boolean result1 = str1.equals("hello");
boolean result2 = str1.equals(str2);
System.out.println(result1); // 输出true
System.out.println(result2); // 输出false
7. equalsIgnoreCase(String anotherString)
将此字符串与另一个字符串比较,忽略大小写差异。
例如:
String str1 = "Hello"; String str2 = "hello"; boolean result = str1.equalsIgnoreCase(str2); System.out.println(result); // 输出true
8. startsWith(String prefix)
测试此字符串是否以指定的前缀开始。
例如:
String str = "hello";
boolean result = str.startsWith("he");
System.out.println(result); // 输出true
9. endsWith(String suffix)
测试此字符串是否以指定的后缀结束。
例如:
String str = "hello";
boolean result = str.endsWith("lo");
System.out.println(result); // 输出true
10. toLowerCase()
使用默认语言环境将字符串转换为小写。
例如:
String str = "hello"; String result = str.toLowerCase(); System.out.println(result); // 输出hello
11. toUpperCase()
使用默认语言环境将字符串转换为大写。
例如:
String str = "hello"; String result = str.toUpperCase(); System.out.println(result); // 输出HELLO
12. trim()
返回字符串的副本,删除前导和尾随空格。
例如:
String str = " hello "; String result = str.trim(); System.out.println(result); // 输出hello
13. replace(char oldChar, char newChar)
返回一个新字符串,其中所有出现的oldChar被替换为newChar。
例如:
String str = "hello";
String result = str.replace('l', 'L');
System.out.println(result); // 输出heLLo
14. split(String regex)
将此字符串拆分为分隔符匹配的字符串数组。
例如:
String str = "hello world";
String[] result = str.split(" ");
System.out.println(result[0]); // 输出hello
System.out.println(result[1]); // 输出world
