String类

        String类是不可变类,即一旦一个String对象被创建以后,包含在这个对象中的字符序列式不可改变的,直至这个对象被销毁。

String类里常用的几个方法:

 

String concat(String str):将该String对象与str连接在一起。与java提供的字符串连接运算符+的功能是相同。

boolean endsWith(String suffix):返回该String对象是否已suffix结尾。

boolean startsWith(String prefix):返回该String对象是否以prefix开始。

boolean equals(Object anObject):将该字符串与指定对象比较,如果两者包含的字符序列相等则返回true。否则返回false。

boolean equalsIgnoreCase(String str):与前一个方法基本类似,只是忽略字符的大小写。

void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin):该方法将字符串从srcBegin开始,到srcEnd结束的字符复制到dst字符数组中,其中dstBegin为目标字符数组的起始复制位置。

int indexOf(int ch):找出ch字符在该字符串中第一次出现的位置。

int indexOf(String str):找出str子字符串在该字符串中第一次出现的位置。

int length():返回当前字符串长度。

String replace(char oldChar,char newChar):将字符串中第一个oldChar替换成newChar。

String substring(int beginIndex):取从beginIndex位置开始到结束的子字符串。

String substring(int beginIndex,int endIndex):取从beginIndex位置开始到endIndex位置的子字符串。

char[] toCharArray():将该String对象转换成char数组。

String toLowerCase():将字符串转换成小写。

String toUpperCase():将字符串转换成大写。

static String valueOf(X x):一系列用于将基本类型值转化为String对象的方法。

 String类是不可变的,String的实例一旦生成就不会再改变。

String s0="hello";

String s1="hello";

String s2="he"+"llo";

System.out.println(s0==s1);

System.out.println(s0==s2);

System.out.println(new String("hello")==new String("hello"));

上面程序运行结果为:

true

true

false

 
    程序最后一行输出false比较容易理解:因为两次new出来的String对象不是同一个对象,所以使用==比较返回false。
    Java会确保每个字符串常量只有一个,不会产生多个副本。例子中的s0和s1中的"hello"都是字符串常量,它们在编译期就被确定,所以s0==s1返回true;而"he"和"llo"也都是字符串常量,当一个字符串由多个字符串常量连接而成时,它本身也是字符串常量,所以s2同样在编译期就被解析为一个字符串常量,所以s2也是常量池中"hello"的引用。所以程序输出s0==s1返回true,s1==s2也返回true。
    用new String()创建的字符串不是常量,不能在编译期就确定,所以new String()创建的字符串不会放人常量池中,它们有自己的地址空间。
 
 
   StringBuilder、StringBuffer则提供了系列插入、追加、改变该字符串里包含的字符串序列。而StringBuffer与其用法完全相同,只是StringBuffer是线程安全的。
 

public class TestStringBuilder
{
 public static void main(String[] args)
 {
  StringBuilder sb=new StringBuilder();
  
  sb.append("java");
  sb.insert(0,"hello");
  
sb.insert(5,",");
  System.out.println(sb);

sb.delete(5,6);
  System.out.println(sb);
  sb.reverse();
  System.out.println(sb);
  System.out.println(sb.length());
  System.out.println(sb.capacity());
  sb.setLength(5);
  System.out.println(sb);

 }
}


   StringBuilder类的追加、插入、替换、删除等操作,这些操作改变了StringBuilder里的字符序列,这是StringBuilder与String之间最大的区别:StringBuilder的字符序列是可变的。程序看到StringBuilder的length()方法返回其字符序列的长度,而capacity()返回值则比length()返回值大。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值