字符串拆分與截取


范例:實現字符串的拆分處理

全拆分

String str = "hello world hello mldn";

String result [] = str.split(" ");

for(int x = 0 ; x < result.length ; x++)

{

  System.out.println(result[x]);

}

部分拆分

String str = "hello world hello mldn";

String result [] = str.split(" ",2);

for(int x = 0 ; x < result.length ; x++)

{

  System.out.println(result[x]);

}

拆分ip地址

String str = "192.168.1.1";

String result [] = str.split("\\.");   如果發現有些拆分不了,需使用\\進行拆分

for(int x = 0 ; x < result.length ; x++)

{

  System.out.println(result[x]);

}

String str = "SMITH:10 | ALLEN :20";

String result [] = str.split("\\|");   如果發現有些拆分不了,需使用\\進行拆分

for(int x = 0 ; x < result.length ; x++)

{

  String temp [] = result[x].split(":");

  System.out.println(temp[0] + " = " + temp[1]);

}

字符串截取

完整的字符串中截取部分內容

String str = "helloworld";

System.out.println(str.substring(5));  // world

 System.out.println(str.substring(0,5));  // hello

 

范例:觀察trim()方法的使用

去掉字符串中左右的空格 保留中間空格

String str1 = "helloworld";

String str2 = "hello".contat("world");               // 

System.out.println(str1 == str2);                   // false

System.out.println(str1 == str2.intern());       // true

System.out.println(str2);       // helloworld

 

范例:觀察isEmpty()方法

Syetem.out.println("hello".isEmpty());            //false

Syetem.out.println("".isEmpty());    //true

Syetem.out.println(new String().isEmpty());  //true

 

范例:實現首字母大寫

String name = "smith";

System.out.println(initcap(name));

public  static String initcap(String str)

{

  if(str == null || "".equals(str))

  {

    return str ;

  }

  if(str.length()>1)

  {

    return str.substring(0,1).toUpperCase() + str.substring(1);

  } 

  return str.UpperCase();

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM