字符串的声明
-
双引号赋值
String x = "a"; String y = "a"; System.out.println(x==y); //true System.out.println(x.equals(y)); //true
同一个String字面值无论被创建多少次,始终只有一个内存地址被分配;
“==”:引用指向同一地址
“equal”:内存中内容相同
-
构造器创建
String a = new String("abcd"); String b = new String("abcd"); System.out.println(a==b); //false System.out.println(a.equals(b)); //true
不同对象会在堆中分配不同的内存空间;
-
其他类型转换
…
字符串的连接
String s1 = new String("hello ");
String s2 = new String("world");
System.out.println(s1 + s2);
int booktime = 4;
System.out.println("我每天看书" + booktime +"小时");
-
字符串之间相连:直接连起来
-
其他类型相连:自动调用toString()转换成字符串进行连接
获取字符串信息
-
字符串长度:
.length()
str.length();
-
字符查找:
.indexOf()
、.lastIndexOf()
String str = "hello world"; int index1 = str.indexOf("l"); //index1=2 int index2 = str.lastIndexOf("l"); //index2=9
indexOf():返回首次匹配的位置
lastIndexOf():返回最后一次匹配的位置
-
字符获取:
.charAt()
String str = "hello world"; str.charAt(4); //o
-
字符替换:
.replace()
String str = "hello world"; str.replace("e","E") //hEllo world
-
子串获取:
.substring()
String str = "hello world"; str.substring(0,3) //hel
-
空格去除:
.trim()
String str = " hello world "; str.trim() //hello world
去除首尾空格
-
开头/结尾判断:
.startsWith()
、.endsWith()
String str = "hello world"; str.startsWith("he"); //true str.endsWith("rl") //false
-
字符串相等判断:
.equals()
判断内存中的值是否相同,而不是地址是否相同(==)
-
字符大小写转换:
.toLowerCase()
、.toUpperCase()
String str = "abc DEF"; System.out.println(str.toLowerCase());
-
字符串分割:
.split()
String str = "abc DEF"; String[] newstr = str.split(" "); for (int i = 0; i < newstr.length; i++) { System.out.println(newstr[i]); }
格式化字符串
String.format()
用于创建格式化的字符串
-
常规类型格式化
String str = String.format("%d", 400/2); //结果以十进制显示
-
日期格式化
Date date = new Date; String s = String.format("%te", date);
-
时间格式化
Date date = new Date; String hour = String.format("%tH", date); String minute = String.format("%tM", date);