String類的常用方法總結

package com.yangfan.string;
class StringDemo{
 
 //取出字符串中指定位置的字符
 public void charAt(){
  String str = "hello";
  char c =str.charAt(3);
  System.out.println(c);
 }
 //由字符串--->字符數組
 public void charArray(){
  String str="hello world";
  char c[] = str.toCharArray();
  for(int i=0;i<c.length;i++){
   System.out.print(c[i]+",");
  }
  String str1 =new String(c);//將全部的字符數組變爲String
  String str2 = new String(c,0,6);
 }
 //字節數組--->字符串
 public void ByteArray(){
  String str = "hello world";
  byte b[] = str.getBytes();
  String  str1 = new String(b);//變回字符串
  }
 //替換內容
 public void replaceContext(){
  String str = "hello world";
  String newStr = str.replaceAll("l", "x");
 }
 //字符串截取
 public void substring(){
  String str = "hello world";
  String sub1 = str.substring(6);
  String sub2 = str.substring(0, 3);
 }
 //字符串拆分
 public void split(String regex){
  String str ="hello world";
  String s []=str.split(regex);//按regex條件拆分
  for(String st:s){
   System.out.println(s);
  }
 }
 //字符串查找(直接查找)
 public void contains(String s){
  String str ="hello world";
  System.out.println(str.concat("hello"));//結果是true
 }
 public void indexOf(){
  String str ="hello world";
  if(str.indexOf("hello")!=-1){
   System.out.println("查找到要的內容!");
  }
 }
 /*
  * 去掉左右空格:public String trim();
  * 取得字符串長度:public int length();
  * 轉大寫:public String toUpperCase();
  * 轉小寫:public String toLowerCase();
  * 
  */
 //按要求拆分:TOM:89|JERRY:90|TONY:79
 //拆成:TOM ->89 JERRY ->90 TONY -> 79
 public void splitDemo(){
  String str = "TOM:89|JERRY:90|TONY:79";
  String[] str2 =str.split("//|");
  for(String st:str2){
   String[] s2=st.split(":");
      System.out.println(s2[0]+"-->"+s2[1]);
  }
  
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章