String类是用来处理字符串的类,他的使用非常频繁。但是注意,他是引用类型。
String类创建对象的方法
//String的创建实例化
//直接创建并赋值String s1="第一种创建方式";
//通过构造方法创建并赋值
Sring s2=new String("第二种创建方式");
//通过无惨的构造方法创建 然后赋值
String s3=new String();
s3="第三种创建方式";
String类的比较
基本数据类型做比较是使用==,String类型比较可以使用==?
eg:
public class StringTest {
public static void main(String[] args) {
int a=5;
int b=5;
//基本数据类型可以用==判断是否相等
//==是判断栈里边的值是否相等
System.out.println(a==b);
String s1="abc";
String s2=new String("abc");
System.out.println(s1==s2);
//判断字符串的值是否相等要通过String类中equals方法进行判断
System.out.println(s1.equals(s2));
//一般来说直接输出对象 会输出对象在内存中的地址
//但是String类比较特殊 在直接输出Strng对象时,系统会默认调用toString方法输出字符串
System.out.println(s2);
}
}
String类与数组装换
字符串==》数组(借助String类型的toCharArray()方法)
eg:
public class StringTest {
public static void main(String[] args) {
//数组--》字符串
char[] cs={'h','e','l','l','o'};
String s=new String(cs);
System.out.println(s);
//字符串--》数组
String s2="world";
char[] cs2=s2.toCharArray();
for(int i=0;i<cs2.length;i++){
System.out.println(cs2[i]);
}
}
}
String类的常用方法
比较字符串的内容是否相等
比较字符串的内容是否相等 忽略大小写
判断某个字符是否在字符串中
eg:
public class StringTest{
public static void mamin(String[] args){
String s="hello";
//求字符串的长度
System.out.println(s.length());
//判断字符串是否相等
System.out.println("Hello".equalsIgnoCase(s));
//判断某个字符串是否在字符串中(如果不在,返回值为-1)
System.ut.println(s.indexOf('1'));
}
}
取出字符串中指定位置的字符
去掉字符串首尾空格
截取字符串的一部内容
eg:
public class StringTest{
public static void main(String[] args){
String s="hello word";
//取出字符串中指定位置的字符(下标从0开始)
char c=s.charAt(1);
System.out.println(c);
//去掉空格(去除字符串起始和结束位置的空格)
s=s.trim();
System.out.println(s);
//***截取字符串
String s2=s.substring(3);
//去除索引前的字符串 保留索引后的
System.out.println(s2);
//截取字符串从起始索引开始到结束索引(包含起始索引的字符,不包含结束索引的字符)
String s3=s.substring(3,7);
System.out.println(s3);
//获取文件的扩展名
String fileName="16级javaSe作业.txt";
int index=fileName.lastIndexOf('.');
String fileType=fileName.substring(index+1);
System.out.println(fileType);
}
}
字符串大小写转换
判断字符串是否以XXX开头或结尾
替换字符串中某个字符
按照指定方式分割字符串
public class StringTest{public static void main(String[] args){
String s="Hellor world";
//转化为小写
System.out.println(s.toLowerCase());
//转化为大写
System.out.println(s.toUpperCase());
//判断字符串是否以***开头
System.out.println(s.startsWith("He"));
//判断字符串是否以***结尾
System.out.println(s.trim().endsWith("ld"));
//替换某个字符串中的字符
System.out.println(s.replace'l','r');
System.out.println(s.replaceFirst("l","r"));//只替换第一个匹配的字符串
System.out.println(s.replaceAll("or","d"));
//按指定方式分割字符串
String s2="你好啊,我很好";
String[] ss=s2.split(",");
for(int i=0;i<ss.length;i++){
System.out.println(ss[i]);
}
}
}
String StringBuffer StringBuilder的区别
String值不可变(堆中的值)
String字符串拼接时占用内存多
StringBuffer和StringBuilder值可变
StringBuilder线程安全 StringBuffer效率高线程不安全