//太久没用Java,对语法不熟悉了,大概整理复习下加深印象
tips:String类内部指向的串是常量,每次改变后会创建新的对象指向它,原来的可能被自动回收机制回收。
String经常改变尽量用StringBuilder那些...
直接写的字符串常量被当做String类的对象.
两个String对象内容相同指向的地址其实一样.
package test;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = new String("hello world");
System.out.println(s.charAt(2)); //求指定下标对应字符
System.out.println(s.substring(1)); //求从指定下标开始到结尾的子串
System.out.println(s.substring(1,4)); //求指定下标之间的子串,区间左闭右开
System.out.println(s.compareTo("hello worla")); //字符串比较,返回二者字典序相减的值
System.out.println(s.compareToIgnoreCase("Hello World")); //字符串比较,忽略大小写
System.out.println(s.equals("hello world")); //比较字符串内容是否相同
System.out.println(s.concat("123") + " 123"); //比较字符串连接效果和+号一样
System.out.println(s.indexOf("worl")); //查找子串或子字符第一次出现位置,没有出现返回-1
System.out.println(s.toUpperCase()); //大小写转换
System.out.println(s.replaceAll("h", " ")); //字符串替换
System.out.println(s.trim()); //去掉首尾空白符
System.out.println(s.contains("hello")); //是否包含字符串
String[] t = s.split(" ");
for (String string : t) {
System.out.println(string);
}
System.out.println(String.valueOf(12.3)); //其它数据类型转换为string
}
}
输出结果:
l
ello world
ell
3
0
true
hello world123 123
6
HELLO WORLD
ello world
hello world
true
hello
world
12.3