---<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流!---
String类及String类的相关操作方法
(1)String的两种实例化方式public String(String origiral)///可以接收一个String类的对象,并重新实例化String对象,
除了此方法之外String还可以采用直接赋值的方式进行对象的实例化。
public class StringDemo01{
public static void main(String args[]){
String str1 = "hello" //使用直接赋值的方式完成
String str2 = new String("MLDN") //通过构造方法完成
System.out.println(str1 + str2) //进行字符串的连接操作
}
}
(2)String的比较方式
public class StringDemo02{
public static void main(String args[]){
String str1 = "hello" //使用直接赋值的方式完成
String str2 = new String("hello") //通过构造方法完成
String str3 = str2 //通过构造方法完成
System.out.println("str1 == str2 --> " + (str1==str2)) // false
System.out.println("str1 == str3 --> " + (str1==str3)) // false
System.out.println("str2 == str3 --> " + (str2==str3)) // true
}}
“= =”实际上比较的是两个对象的地址是否相等,具体的是比较地址的值,因为地址是以数值的形式存在的
但是如果需要比较字符串的内容,就需要使用String类中的equals()方法完成比较:
public boolean equals(String str) 以上程序修改为str1.equals(str2)
一个字符串使用" "括起来,那么一个字符串常量实际上本身就属于String的一个匿名对象
(4) String的两种实例化方式的区别
String str1="hello"///表示在堆中开辟一个空间并将该空间地址赋值给栈中的str1
String str1=new String("hello")///表示先在堆中开辟一个字符串的匿名对象,然后在用new开辟一片新的空间,
并将原对象值赋值给新的空间中,并将新开辟的空间地址赋值给栈内的.
str1,而原来的匿名对象所在空间为垃圾空间
public class StringDemo05{
public static void main(String args[]){
String str1 = "hello" //使用直接赋值的方式完成
String str2 = "hello" //使用直接赋值的方式完成
String str3 = "hello" //使用直接赋值的方式完成
System.out.println("str1 == str2 --> " + (str1==str2))
System.out.println("str2 == str3 --> " + (str2==str3))
System.out.println("str1 == str3 --> " + (str1==str3))
}
}
结果输出的都是true,表示的是同一个空间引用,因为对于String来讲使用直接赋值的方式会在字符串池中保存,
如果之后再声明字符串的时候发现内容一样,则不会重新开辟空间,而是从内存池中取出数据继续使用。
(5)String类的常用操作方法
char charAt(int index)//根据字符串中的索引找到指定位置的字符
public char[] toCharArray()//将字符串变为字符数组
public String(char[] value)//将全部的字符数组变为String类型
public String(char[] value,int offest,int count )//将数组中的offest起始位置开始
,长度为count的字符转换为数组
String concat(String str)//字符串的链接也可以用+号连接
public byt[] getBytes()//将字符串变为字节数组
public String(byte[] bytes)//将字节数组全部变为字符串
public String(byte[] bytes,int offset ,int length)//将字节数组的offset开始,长度为length变为字符串
public boolean startsWith(String prefix)//判断是否指定的字符串开头
public boolean endsWith(String suffix)//判断是否以指定的字符串结尾
public String replaceAll(String regex,String replacement)//将字符串中的regex采用replacement替换
public String substring(int beginIndex)//从beginIndex开始全部截取
public String substring(int beginIndex,int endIndex)//从beginIndex开始到endIndex进行截取
public String[] split(String regex)//按照字符串regex拆分成字符串数组,如果两个引号见什么都不写则全部拆分 (11) 字符串查找
public int indexOf(String str)//查找指定字符串的位置,如果查找不到返回-1,查找到返回0
if(str.indexOf(str2)!=-1)//返回的值不等于-1则查找到
public int indexOf(String str,int fromIndex )//从fromIndex开始查找str的位置
public boolean contains(String s)//查找指定的字符串,返回值我true或false
public String trim()//去掉左右空格
public int length()//取得字符串长度
public String toUpperCase()//转换成大写
public String toLowerCase()//转换成小写