字符串String
一、常用方法
1、判断两个字符串是否相等
equals
:
通常推荐使用 "abc".equals(str);
而不是 str.equals("abc");
String str = null;
"abc".equals(str); //推荐
str.equals("abc"); //不推荐 当str为null时,会抛出空指针异常。
引申:通常比较一个常量和一个变量的时候,推荐把常量字符放在前面。
2、 忽略大小写:
public boolean equalsIgnoreCase(String str)
3、获取字符串长度:
public int length()
4、拼接字符串
public String concat(String str)
String str1 = "hello";
String str2 = "world";
String str3 = str1.concat(str2);
5、获取指定索引位置的字符
public char charAt(int index)
String str = "hello";
char s = str.charAt(0);//s为字符'h’
6、查找参数 字符串在本字符串中首次出现的索引位置 , 如果没有返回-1.
public int indexOf(String str)
String str = "helloworld";
int index = str.indexOf("ll"); //index值为2.
7、字符串截取方法
public String subString(int index);//从参数位置开始一直到结尾。
public String subString(int begin , int end); //[begin , end) 左闭右开
String str = "helloworld";
String str1 = str.substring(2);
System.out.println(str1); //lloworld
String str2 = str.substring(2 , 4);
System.out.println(str2); //ll
8、字符串拆分成字符数组,并返回
public char[] toCharArray
String str = "helloworld";
char[] str1 = str.toCharArray();
for (char c : str1){
System.out.print(c +" "); //h e l l o w o r l d
}
9、字符串替换
public String replace(String oldStr , String newStr);
String str = "helloworld";
String str1 = str.replace('l' , '&');
System.out.println(str1); //he&&owor&d
10、分割字符串
public String[] split(String regex);//按照参数规则, 拆分成若干个部分
split
切分规则其实是正则表达式。 切分 '.'
需要加两个反斜杠 \\.