package com.bjsxt.wrap;
public class TestStringMehtods {
public static void main(String[] args ) {
byte [] b ={97,98,99};
System. out .println( new String( b )); //byte[]---->String
/**(1)byte [] getBytes()*/
String str = "helloworld" ; //String -->byte[]
byte [] buf = str .getBytes();
for ( byte by : buf ){
System. out .println( by );
}
/*(2) int indexOf( int /String) int indexOf( int /String , int fromIndex)*/
System. out .println( str .indexOf(101)); // 在索引为 1 的位置上,找到返回索引
System. out .println( str .indexOf( 'l' )); // 自动类型转换 char--> int 2,
System. out .println( str .indexOf( "e" ));
System. out .println( str .indexOf( "e" ,3)); //-1 找不到返回 -1
/**(3) int lastIndexOf( int /String) int lastIndexOf( int /String, int fromIndex)*/
System. out .println( str .lastIndexOf( 'o' )); //o 最后一次出现的位置 6
System. out .println( str .lastIndexOf( 'o' ,3)); //-1
System. out .println( str .lastIndexOf( "o" , 7)); //6
/**(4)boolean isEmpty() 字符串的长为 0 时 -- 》 true*/
System. out .println( "" .isEmpty());
String s = null ;
//System.out.println(s.isEmpty());
/**(5)replace(char oldchar ,char newchar ) replace(CharSequence c,CharSequence c2)*/
System. out .println( str );
str = str .replace( 'o' , ' 中 ' ); // 使用 " 中 " 替换所有的 'o'
System. out .println( str );
/**(6)String [] split(String s) 1998-8-9*/
String sDate = "1998-8-9" ;
String [] ss = sDate .split( "-" );
for (String string : ss ) {
System. out .println( string );
}
/**(7)CharSequence subSequence( int startIndex, int endIndex)*/
CharSequence sss = str .subSequence(2, 5); // 含头不含尾
System. out .println( sss ); // 调用了 toString 方法
// 如何将 CharSequence 转 String -->toString()
/**(8)String subString( int startIndex, int endIndex)*/
str = str .substring(2, 5); // 含头不含尾
System. out .println( str );
/**(9)char []toCharArray()*/
char [] c = str .toCharArray();
System. out .println( " 数组的长度 :" + c . length );
for ( char d : c ) {
System. out .println( d );
}
/**(10)String trim()*/
String strr = " hello world " ;
System. out .println( strr .length());
strr = strr .trim();
System. out .println( strr + strr .length());
/**(11)staticString valueOf( 任意类型 )*/
String s1 =String. valueOf (12);
String s2 =String. valueOf ( true );
String s3 =String. valueOf ( new char []{ 'a' , 'b' });
String s4 =String. valueOf ( new Integer(12)); // 进行了向上类型转换,转成了 Object 类型 Object obj =new Integer(12);
}
}
String类中常用方法总结【二】
猜你喜欢
转载自blog.csdn.net/wyqwilliam/article/details/92739884
今日推荐
周排行