String常用的方法

String常用的方法

Contents:

1.        length()

2.        substring()

3.        toCharArray()

4.        charAt()

5.        indexOf()



public class StringMethods {

	public static void main(String[] args) {
		String s1 = new String();
		String s2 = "billryan";
		System.out.println( "s2 = " + s2 );
//		Method 1 : length()
		System.out.println( "s2.length() = " + s2.length() );	// output 8
		
//		Method 2 : substring()
		System.out.println( "s2.substring(4,7) = " +s2.substring(4,8) );  //output "ryan"

		StringBuilder s4 = new StringBuilder(s2.substring(4,8));
		StringBuilder s5 = s4.append("bill"); 	//return "ryanbill"
//		StringBuilder 可以直接输出,为什么还toString()
		System.out.println( "s5 = " +s5 );  //output "ryanbill"
		System.out.println( "s5.toString() = " + s5.toString() ); //output "ryanbill"
		
//		Method 3 : toCharArray()
		// convert string to char array 
		char [] s2Char = s2.toCharArray();
		System.out.println( "s2.Char[4] = " +s2Char[4] );	//output 'r'
//		Method 4 : charAt()
		// char at index 4
		System.out.println( "s2.charAt(4) = " +s2.charAt(4) );	//output 'r'
//		Method 5 : indexOf()
		System.out.println( "s2.indexOf('r') = " +s2.indexOf('r') );	//output 4



	}

}
output:
s2 = billryan
s2.length() = 8
s2.substring(4,7) = ryan
s5 = ryanbill
s5.toString() = ryanbill
s2.Char[4] = r
s2.charAt(4) = r
s2.indexOf('r') = 4




你可能感兴趣的:(数据结构和算法)