JAVA String类和StringBuffer类 的区别



String类和StringBuffer类

  位于java.lang包中,这个包中的类使用时不用导入

  String类一旦初始化就不可以改变,而stringbuffer则可以。它用于封装内容可变的字符串。它可以使用tostring()转换成string字符串。

  String x=”a”+4+”c”编译时等效于String x=new StringBuffer().append(“a”).append(4).append(“c”).toString();

  字符串常量是一种特殊的匿名对象,String s1=”hello”;String s2=”hello”;则s1==s2;因为他们指向同一个匿名对象。

  如果String s1=new String(“hello”);String s2=new String(“hello”);则s1!=s2;

  /*逐行读取键盘输入,直到输入为“bye”时,结束程序

  注:对于回车换行,在windows下面,有'\r'和'\n'两个,而unix下面只有'\n',但是写程序的时候都要把他区分开*/

  
public class readline 

  { 

  public static void main(String args[]) 

  { 

  String strInfo=null; 

  int pos=0; 

  byte[] buf=new byte[1024];//定义一个数组,存放换行前的各个字符 

  int ch=0; //存放读入的字符 

  system.out.println(“Please input a string:”); 

  while(true) 

  { 

  try 

  { 

  ch=System.in.read(); //该方法每次读入一个字节的内容到ch变量中。 

  } 

  catch(Exception e) 

  { 

  } 

  switch(ch) 

  { 

  case '\r': //回车时,不进行处理 

  break; 

  case '\n': //换行时,将数组总的内容放进字符串中 

  strInfo=new String(buf,0,pos); //该方法将数组中从第0个开始,到第pos个结束存入字符串。 

  if(strInfo.equals("bye")) //如果该字符串内容为bye,则退出程序。 

  { 

  return; 

  } 

  else //如果不为bye,则输出,并且竟pos置为0,准备下次存入。 

  { 

  System.out.println(strInfo); 

  pos=0; 

  break; 

  } 

  default: 

  buf[pos++]=(byte)ch; //如果不是回车,换行,则将读取的数据存入数组中。 

  } 

  } 

  } 

  } 

String类的常用成员方法

  1、 构造方法:

  
String(byte[] byte,int offset,int length);这个在上面已经用到。


  2、 equalsIgnoreCase:忽略大小写的比较,上例中如果您输入的是BYE,则不会退出,因为大小写不同,但是如果使用这个方法,则会退出。

  3、 indexOf(int ch);返回字符ch在字符串中首次出现的位置

  4、 substring(int benginIndex);

  5、 substring(int beginIndex,int endIndex);

  返回字符串的子字符串,4返回从benginindex位置开始到结束的子字符串,5返回beginindex和endindex-1之间的子字符串。

  基本数据类型包装类的作用是:将基本的数据类型包装成对象。因为有些方法不可以直接处理基本数据类型,只能处理对象,例如vector的add方法,参数就只能是对象。这时就需要使用他们的包装类将他们包装成对象。

  例:在屏幕上打印出一个*组成的矩形,矩形的宽度和高度通过启动程序时传递给main()方法的参数指定。

  
public class testInteger 

  { 

  public static void main(String[] args) 

  //main()的参数是string类型的数组,用来做为长,宽时,要转换成整型。 

  { 

  int w=new Integer(args[0]).intValue(); 

  int h=Integer.parseInt(args[1]); 

  //int h=Integer.valueOf(args[1]).intValue(); 

  //以上为三种将字符串转换成整形的方法。 

  for(int i=0;i 

  { 

  StringBuffer sb=new StringBuffer(); //使用stringbuffer,是因为它是可追加的。 

  for(int j=0;j 

  { 

  sb.append('*'); 

  } 

  System.out.println(sb.toString()); //在打印之前,要将stringbuffer转化为string类型。 

  } 

  } 

  } 

  比较下面两段代码的执行效率:

  (1)String sb=new String(); 

  For(int j=0;j 

  { 

  Sb=sb+’*’; 

  } 

  (2) StringBuffer sb=new StringBuffer(); 

  For(int j=0;j 

  { 

  Sb.append(‘*’); 

  } 


  (1) 和(2)在运行结果上相同,但效率相差很多。

  (1) 在每一次循环中,都要先将string类型转换为stringbuffer类型,然后将‘*’追加进去,然后再调用tostring()方法,转换为string类型,效率很低。

  (2) 在没次循环中,都只是调用原来的那个stringbuffer对象,没有创建新的对象,所以效率比较高。

你可能感兴趣的:(StringBuffer)