String字符串:
String 不可变的字符串 没有直接操作字符串的增加删除改变的方法
StringBuilder 可变字符串
1.String类使用final修饰 不能子类化
2.创建字符串
String detail1 = new String(s: "中国");
detail1变量在栈上定义
new的对象在堆里面
"中国" 在常量区
MyClass.java
public class MyClass {
public static void main(String[] args){
//常量字符串的创建
String country = "中国";
String city = "重庆";
//使用构造方法创建
String detail = new String();
String detail1 = new String(s: "中国");
char[] name = new char[] {'j', 'a', 'c', 'k'};
String s_name = new String(name);
System.out.println(s_name);
// == 比较的是对象本身
// equals比较的是内容
// compareTo 获取大小关系 1: a>b 0: a=b -1: a<b
System.out.println(country == detail1);//false
System.out.println(country.equals(detail1));//true
System.out.println(country.compareTo("中国"));//0
//字符串的长度 length
for (int i = 0; j < s_name.length(); i++){
//使用charAt获取i对应的字符
System.out.println(s_name.charAt(i));
}
//判断字符串是否为空
if(s_name.length() > 0){ }
if (s_name.isEmpty()) { }
//判断字符串是不是以某个字符串开头
String url = "http://www.baidu.com";
System.out.println(url.startWith("http"));//true
System.out.println(url.startWith(s: "www", i: 8));//false
System.out.println(url.startWith(s: "www", i: 7));//true
//判断字符串是不是以某个字符串结尾
String pic = "http://www.baidu.com/image/1.jpg";
if (pic.endsWith("jpg")){
System.out.println("jpg格式的图片");
} else {
System.out.println("不是jpg格式的图片");
}
//获取某个子字符串在字符串的起始位置
String pic1 = "http://www.baidu.www.com/image/1.png";
System.out.println(pic1.indexOf("www"));//7
System.out.println(pic1.indexOf(s: "www", i: 8));//17
//获取子字符串
System.out.println(pic1.substring(7));//www.baidu.www.com/image/1.png
System.out.println(pic1.substring(i: 7, i1: 10));//www
//字符串的替换 (并没有覆盖原字符串)
System.out.println(pic1.replaceAll(s: "baidu", s1: "google"));//http://www.google.www.com/image/1.png
System.out.println(pic1);//http://www.baidu.www.com/image/1.png
//字符串分割
String[] split = pic1.split(s: "/");
//不能直接输出,直接输出的是哈希值
for (String comp: split) {
System.out.println(comp); //http: www.baidu.com image 1.png
}
//将字符串末尾的空格去除
System.out.print(pic1);
System.out.print("-");
//http://www.baidu.www.com/image/1.png -
System.out.print(pic1.trim());
System.out.print("-");
//http://www.baidu.www.com/image/1.png-
//字符串的拼接
System.out.println(1)
}
}