Java String 类
1、创建字符串
String s = "HelloWorld";//直接创建
String ss = s;//相同引用
String sss = new String();//String 类对象创建
String创建的字符串储存到公共池中,而new 创建的字符串对象在堆中
char[]c = {'h','e','l','l','o'};
String s1 = new String(c);
byte[] b = {99,98,97};
String s2 = new String(b);
注意,String类是不可改变的,所以一旦创建String类对象,那么他的值就无法改变了
如果你觉得它发生改变了,那么肯定是创建了一个新的String类对象
2、字符串长度
String s = "HelloWorld";
System.out.println(s.length());
3、连接字符串
contact.(连接对象)
String s = "HelloWorld";
String ss = s.concat("java");
System.out.println(ss);
4、字符串比较
equals
String s = "HelloWorld";
String ss = "HelloWorld";
char[] c = new char[]{'H','e','l','l','o','W','o','r','l','d'};
String sss = new String(c);
System.out.println(s.equals(ss));
System.out.println(s.equals(sss));
System.out.println(s==sss);
equals比较的是字符串的内容,而==比较的是字符串的地址,所以即使内容一样
也会出现false
true
true
false
不区分大小写的:equalsIgnoreCase
package ccode;
public class zongjie {
public static void main(String[] args) {
String s = "HELlOWorlD";
char[] c = new char[]{'H','e','l','l','o','W','o','r','l','d'};
String sss = new String(c);
System.out.println(s.equalsIgnoreCase(sss));
}
}
输出结果:true
5、获取指定索引位置的单个字符
charAt(int index)
package ccode;
public class zongjie {
public static void main(String[] args) {
String s = "HELlOWorlD";
char[] c = new char[]{'H','e','l','l','o','W','o','r','l','d'};
String sss = new String(c);
char t = sss.charAt(2);
System.out.println(t);
}
}
此时t指的是字符串sss中第三个元素(索引位置是2),也就是l
6、查找参数字符在本字符中首次出现的索引位置,若果没有,返回-1
indexOf(字符串)
package ccode;
public class zongjie {
public static void main(String[] args) {
String s = "HELlOWorlD";
char[] c = new char[]{'H','e','l','l','o','W','o','r','l','d'};
String sss = new String(c);
int len = sss.indexOf("llo");
System.out.println(len);
int len2 = sss.indexOf("ssss");
System.out.println(len2);
}
}
输出结果:
2
-1
7、字符串的截取:
substring(int index);
substring(int begin,int end);
和c++的substr用法一样,第一个是截取从index位置到结束的字符串;
第二个是截取从begin到end(左闭右开)区间的字符串
8、字符串的替换:
replace(a,b)//把所有的a都换成b
代码示例:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s = "hello";
String ss = s.replace("l","t");
System.out.println(ss);
}
}
输出样例
hetto
9、字符串的分割(放到数组里):
String[] ss = s.split(“要分切的标志”)
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s = "he,ll,o";
String[] c = s.split(",");//按照,进行分切
System.out.println(c);
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
}
输出样例:
he
ll
o
需要注意的是,当字符为“.”的时候,需要使用“\\.”才行