①特性:
- String类是final类,意味着String类不能被继承,所有的方法都默认为final方法
- String类是通过char数组来保存字符串的
- String对象一旦被创建就不能改变了
- 当我们创建一个新的字符串是,JVM首先会检查字符串常量池,如果已经存在,就直接取出该字符串的实例引用,如果不存在,则实力会该字符串,并放入常量池中
②常用方法
- equals(Object c)
- toUpperCase()
- toLowerCase()
- isEmpty()
- length()
- compareTo(String str)
- compareToIgnoreCase(String str)
- contains(charSequence cs)
- concat(String str)
- indexOf(String str)
- indexOf(String str,int fromIndex)
- lastIndexOf(String str)
- lastIndexOf(String str,int fromIndex)
- charAt(int index)
- endsWith(String suffix)
- equalsIgnoreCase(String str)
- intern()
- subString(int beginIndex)
- subString(int beginIndex,int endIndex)
- split(String regex)
- split(String regex,int limit)
- startsWith(String prefix)
- startsWith(String prefix,int toffset)
- toCharArray()
- toString()
- trim()
③示例
equals/toUpperCase/toLowerCase/isEmpty/length/compareTo/contains/concat(String str)/compareToIgnoreCase
@Test
public void test1() {
String str = "abc";
System.out.println("abc".equals(str));
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println(str.isEmpty());
System.out.println(str.length());
String str2 = "5";
System.out.println(str.compareTo(str2));
System.out.printIn(str.compareToIgnoreCase(str2));
System.out.println(str.concat(str2));
System.out.println(str.contains("a"));
}
indexOf/lastIndexOf/charAt
@Test
public void test2() {
String str = "abcabc";
System.out.println(str.indexOf("b"));
System.out.println(str.indexOf("b",2));
System.out.println(str.lastIndexOf("c"));
System.out.println(str.lastIndexOf("a",3));//从开始的下标反向查找
System.out.println(str.chatAt(2));
}
intern()
https://www.cnblogs.com/dreamroute/p/3650399.html
subString/trim/toCharArray
@Test
public void test4() {
String str1 = "a b cd ";
System.out.println(str1.substring(1));
System.out.println(str1.substring(1, 3)); //>-1 <3
System.out.println(str1.trim()); //去除字符序列左边和右边的空格
char[] chars = str1.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
}
split/startsWith
@Test
public void test5() {
String str1 = "ab cd ef";
String[] strs = str1.split(" ");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
System.out.println(str1.startsWith("b"));
System.out.println(str1.startsWith("b",1));
}