- String对象为不可变对象,只能改变标识符的所对应的地址值,其本身不会改变。
- String对象基础为char[]数组,而其底层的实现为byte[]数组。
常用api:
- charAt(int index) 返回索引出的字符
String s = "helloWorld";
char c = s.charAt(3);
//此处c为'l'
- endsWith(String suffix); 返回一个布尔值,是否以指定元素结尾
boolean b = s.endsWith("World");
//此时b为true
- equals(Object object);返回一个布尔值,是否与指定字符相同。
boolean b2 = s.equals("helloWorld");
//此时b2为true
- indexOf(String str);返回第一册出现指定字符的索引.
int index = s.indexOf("W");
//此时index为5
- lastIndexOf(String str);返回指定字符最后一次出现的索引
int end = s.lastIndexOf("d");
//此时end为9
int length = s.length();
//这里length为10
- replace(String regex, String replacement);将原有字符串中的指定字符全部修改为另一指定字符。
String s2 = s.replace("h","A");
//s2为AelloWorld
- split(String str);返回使用指定字符串切割后的String[]数组。
String[] arr = s.split("Wo");
System.out.println(Arrays.toString(arr));
//输出为:[hello,rld]
- startsWith(String str);字符串是否以指定字符开头
boolean b3 = s.startsWhit("he");
//此时b3为true
- subString(int beginIndex) (包含头尾索引)
- subString(int beginIndex;int endIndex)返回指定源字符串的一部分 (仅包含头部索引)
String sub1 = s.subString(3);
String sub2 = s.subString(3,6);
//sub1为loWorld
//sub2为loW
- toUpperCase() 将该字符串全部转为大写
- toLowerCase() 将该字符串全部转换为小写
String lower = s.toLoweCase();
String upper = s.toUpperCase();