字符串拆分与截取


范例:实现字符串的拆分处理

全拆分

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