java学习笔记(十)----String类和StringBuffer类

***String类和StringBuffer类
--------------------------
String类对象中的内容一旦被初始化就不能再改变
StringBuffer类用于封装内容可以改变的字符串,可以将其它各种类型的数据增加,插入到字符串中,也可以翻转字符串中原来的内容。一旦通过StringBuffer生成了最终想要的字符串,就应该使用StringBuffer.toString方法将其转换成String类,然后,就可以使用String类的各种方法操纵这个字符串了。
用toString方法转换成String类型
String x="a"+4+"c"编译时等效于 String x=new StringBuffer().append("a").append(4).append("c").toString();

字符串常量(如"hello")实际上是一种特殊的匿名String对象
1. String s1="hello"; String s2="hello";
   s1和s2指的是同一个对象  if (s1==s2) 结果是true
2. String s1=new String("hello"); String s2=new String("hello")
   s1和s2指的是不同的对象 if (s1==s2) 结果是flase

例: 逐行读取键盘输入,直到输入内容为"bye"时,结束程序

public class ReadLine {
 public static void main(String[] args) {
  byte[] buf=new byte[1024];
  String strInfo=null;
  int pos=0;
  int ch=0;
  System.out.println("please enter info, input tye for exit:");
  while(true)
  { try{
     ch=System.in.read(); //read()方法会读取一个字节的数据
       }
    catch (Exception ex)
    { ex.printStackTrace();
    }      
   switch(ch)
   { case '/r': break;
     case '/n': strInfo=new String(buf,0,pos);
                if (strInfo.equals("bye"))
                { return;
                }
                else
                { System.out.println(strInfo);
                  pos=0;
                  break;
                }
     default :
          buf[pos++]=(byte)ch;
                  
   }
    }
 } 
}

------------------------------------------
String类的常用成员方法
构造方法
** String(byte[] bytes, int offset, int length)  //将一个字节数组的内容转换成字符串对象,从下标为offset的元素,一直取length个元素的内容
** equalslgnoreCase 是在比较两个字符串时忽略大小写, 比如以上程序中的strInfo.equals("bye")可改为strInfo.equalsIgnoreCase("bye"),这样无论输入大小写的bye都能退出
** indexOf(int ch)方法是用来返回一个字符在该字符串中的首次出现的位置,如果没有这个字符则返回"-1"
   如: System.out.println("hello world".indexOf('o'))  //输出结果为4
  它的另一种形式indexOf(int ch, int fromIndex) 反回的是从fromIndex指定的数值开始,ch字符首次出现的位置.
   如: System.out.println("hello world".indexOf('o',5))  //输出结果为7 
** substring(int beginIndex)  返回的是一个字符串中从beginIndex指定的数值到末尾的一个字符串
   如:   System.out.println("hello world".substring(6)) //返回从第6个字符开始一直到最后的字符,输出world 
  substring(int beginIndex, int endIndex) 返回的是当前字符串中从beginIndex开始到endIndex-1结束的一个字符串
   如:   System.out.println("hello world".substring(6,8)) //输出wo
  (如果beginIndex指定的数值超过了当前字符串的长度,则返回一个空字符串)

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值