学习内容
- 字符串操作
1.字符串操作
基础类库:可不用记住,只需要知道这个类是用来做什么的,知道它里面有些什么方法,有那些单词就可以了
字符串
String 是用来创建一个不可变的字符串的
StringBuilder 是用来创建一个可变的字符串的
a.String类使用final修饰,不能子类化
1.创建字符串
a.常量字符串
String country = "中国";
String city = "重庆";
b.使用构造方法创建
String detial = new String();
String detial1 = new String("中国");
// detial变量在栈上定义
//而new的对象在堆里
// == 比较的是对象本身,所以country和detial1不同
//而equals是用来比较字符串的类容的
//compareTo 获取大小关系 1:a>b,0:a=b,-1:a<b
String country = "中国";
String detial1 = new String("中国");
System.out.println(country == detial1);
System.out.println(country.equals(detial1));
System.out.println(country.compareTo("中国"));
//String常用方法:长度——length;获取i对应的字符——charAt()
char [] name = new char[]{'j','a','c','k'};
String s_name = new String(name);
for(int i =0 ;i<s_name.length();i++){
System.out.println(s_name.charAt(i));
}
(a).判断是否为空
if(s_name.isEmpty()){
}
(b).判断是否是这几个字母开头
String pic = "http://www.baidu.com/";
System.out.println(pic.startsWith("http"));
System.out.println(pic.startsWith("https"));
(c).判断是否是这几个字母结尾
String pic1 = "http://www.baidu.com/image/1.jpg";
String pic2 = "http://www.baidu.com/image/1.png";
String pic3 = "http://www.baidu.com/image/1.jpeg";
if(pic1.endsWith("jpg")||pic1.endsWith("jpeg")||pic.endsWith("png")){
System.out.println("图片");
}else {
System.out.println("不是图片");
}
(d).获取某个子字符串在字符串中的位置
String pic4 = "http://www.baidu.www.com/image/1.jpg";
System.out.println(pic4.indexOf("baidu"));
System.out.println(pic4.indexOf("www",8));
(e).获取子字符串
System.out.println(pic2.substring(4));
System.out.println(pic2.substring(4,17));
(f).字符串的替换
System.out.println(pic2.replace("baidu","google"));
//字符串的分割
String [] split = pic2.split("/");
for(String comp:split){
System.out.println(comp);
}
(g).将字符串末尾的空格去掉
System.out.print(pic2);
System.out.print("----\n");
字符串的拼接 +
自动装箱 自动将基本数据类型转化为java的对象类型
//int ---- integer
//char ----Char
//float ---Float
System.out.println(1);
2.StringBuilder
StringBuilder test = new StringBuilder();
//末尾追加
test.append("my name is ");
test.append("jack");
//查找位置
int start = test.lastIndexOf("jack");
System.out.println(test);
//替换start----end之间的字符串
test.replace(start,start+"jack".length(),"merry");
System.out.println(test);
//删除start----end之间的字符串
test.delete(0,2);
System.out.println(test);
//插入数据
test.insert(0,"my");
System.out.println(test);