一、创建字符串
最简单的方式:
String str = "Hello World";
String类是不可改变的,一旦创建了String对象,那它的值就无法改变了。如果要对字符串做修改,应选择使用StringBuffer或StringBuilder类。
二、拆分字符串
根据正则表达式拆分,具体以“,”拆分为例,分情况说明:
1、
String str = "123,qwe,asd";
String[] output = str.split("\\,");
System.out.println(output.length);
System.out.println(Arrays.toString(output));
输出:
3
[123, qwe, asd]
2、
String str = ",,123,qwe,asd";
String[] output = str.split("\\,");
System.out.println(output.length);
System.out.println(Arrays.toString(output));
输出:
5
[, , 123, qwe, asd]
3、
String str = "123,qwe,,,asd";
String[] output = str.split("\\,");
System.out.println(output.length);
System.out.println(Arrays.toString(output));
输出:
5
[123, qwe, , , asd]
4、
String str = "123,qwe,asd,,,";
String[] output = str.split("\\,");
System.out.println(output.length);
System.out.println(Arrays.toString(output));
输出:
3
[123, qwe, asd]
由此可见:当拆分符在字符串开始位置或中间位置时,会被拆出来作为新的字符串,当字符串在末尾位置,则不会计入新的字符串。
若用空格符拆分字符串,则 String[] output = str.split("\\s+");
需要特别说明的是,当字符串中间位置存在多个空格符时,不会计入新的字符串。String str = " 123 qwe asd ";
String[] output = str.split("\\s+");
System.out.println(output.length);
System.out.println(Arrays.toString(output));
输出:
4
[, 123, qwe, asd]
有时在拆分字符串前需要先对字符串进行检查,如:
String str = "123.qwe.asd";
if(str.contains(".")){
String[] output = str.split("\\.");
System.out.println(Arrays.toString(output));
}else{
throw new IllegalArgumentException(str + "- invalid format!");
}
三、字符串比较,“==”和equals()区别
“==”测试引用同一地址,而equals()测试值是否相等。除非需要检查两个字符串是否是同一个对象,否则应该总是使用equals()方法。
“==”比较是不是同一个对象,equals比较两个对象的内容是否相等。