public class StringMethod {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";
boolean result1 = str1.equals(str2);
boolean result2 = str1.equals(str3);
boolean result3 = str1.equalsIgnoreCase(str3);
System.out.println(result1 + " " + result2 + " " + result3);
int len = str1.length();
System.out.println(len);
String result4 = str1.concat(str3);
System.out.println(result4);
char result5 = str1.charAt(1);
System.out.println(result5);
int result6 = str1.indexOf("ll");
System.out.println(result6);
int result7 = str1.indexOf("a");
System.out.println(result7);
String result8 = str1.substring(2);
String result9 = str1.substring(1, 3);
System.out.println(result8 + " " + result9);
char[] result10 = str1.toCharArray();
for (char x : result10) {
System.out.println(x);
}
byte[] result11 = str1.getBytes();
for (int i = 0; i < result11.length; i++) {
System.out.println(result11[i]);
}
String result12 = str1.replace('l', 'L');
System.out.println(result12);
String str4 = "H,E,L,L,O";
String[] result13 = str4.split(",");
for (String x : result13) {
System.out.println(x);
}
// 特殊
String str5 = "H.E.L.L.O";
String[] result14 = str5.split("\\.");
for (String x : result14) {
System.out.println(x);
}
}
}
输出为:
true false true
5
Hellohello
e
2
-1
llo el
H
e
l
l
o
72
101
108
108
111
HeLLo
H
E
L
L
O
H
E
L
L
O
常用方法:
boolean equals(String str);
boolean equalsIgnoreCase(String str);
int length();
String concat(String str);//拼接字符串
char charAt(int index);//获取索引位置字符
int indexOf(String str);//查找参数字符串在本字符串中首次出现的索引位置,如果没有返回-1
String substring(int begin);//截取字符串,从参数位置到字符串结尾
String substring(int begin,int end);//截取字符串,左闭右开
char[] toCharArray();//将当前字符串拆分为字符数组作为返回值
byte[] getBytes();//获得当前字符串底层的字节数组
String replace(charSequence oldString,charSequence newString);//将所有出现的老字符串替换为新字符串,返回替换后的
String[] split(String regex);//按照参数规则,将字符串切分为若干部分