public static void main(String[] args) {
// 所有字符串字面量都是String类型的对象,eg:"what is"
String s1="what is";
System.out.println("s1:"+s1);//what is
String s2=s1;
//s1+" fuck"实际上是s1所引用的对象“what is”+“ fuck”
//构成新的对象what is fuck,将该对象的手地址付给s1
s1=s1+" fuck";
System.out.println("s1:"+s1);//引用变量s1的直接值(地址值)变了
System.out.println("s2:"+s2);//"what is"这个对象并没变
String str = "What is Java!好";
System.out.println(str.length());//14
//查找字符串的最后一个字符
char c = str.charAt(str.length()-1);
System.out.println(c); //好
//查找"好"在字符串中的位置,
//如果没有找到返回负数
System.out.println("###############");
int index = str.indexOf("z");//返回负数 一般为-1
System.out.println(index);
index = str.indexOf("a");//第一个a出现的位置
System.out.println(index); //2
//从下标为10(包含10)的字符开始查找第一个a的位置,10之前的a不查找
index = str.indexOf("a", 10);
System.out.println(index);
//检查一个字符串命令是否是get开头的
String cmd = "get photo.png";//"put p.png"
if(cmd.startsWith("get ")){
System.out.println("这是一个下载命令");
}
//检查一个文件名是否是 .png 图片文件
String file = "T.png";
if(file.endsWith(".png")){
System.out.println("这是一个图片");
}
//toUpperCase()改变内容时候返回新字符串
//原字符串内容不变
String s = str.toUpperCase();
System.out.println(s);//新字符串
System.out.println(str);
System.out.println("+++++++++++++++");
//如果没有改变内容,返回的“可能”是原字符串
//没有创建新对象,“性能好!”
String ss = s.toUpperCase();
System.out.println(ss);
//s和ss指向同一个对象,说明若没有改变字符串的内容,则不创建新对象
System.out.println(ss==s);//true是同一个对象
//去掉输入用户名可能的两端空白
String name = " \r Tom Jack \t \n";
name = name.trim().toLowerCase();//创建出了两个新对象
System.out.println(name);
//
String email = "liucangsong@gmail.com";
name = email.substring(0,11);//不包含11
String host = email.substring(12);//取从12开始(包括12)往后的全部字符串
System.out.println(name + ","+host);
name=email.substring(0,email.indexOf('@'));
host=email.substring(email.indexOf('@')+1);
System.out.println(name + ","+host);
}
//%1$s是第一个待替换的位置,%2$是第二个待低缓的位置,后面的参数是多个Object类型即将替换前面的参数,与前面的%1和%2按顺序一一对应
String result = String.format("(费用:¥%1$s 时间:%2$s分钟/次)",100,"30");
//result = (费用:¥100 时间:30分钟/次)