java String 操作

package shaohv.String;

public class StringOperate {
	public static void main(String[] args){
		//无论中文英文,都当作一个字符看
		String str="i'm 朱绍辉";
		System.out.println(str.charAt(5));
		
		/*
		 * 1. compareTo/compareToIgnoreCase
		 */
		String str1 = "abc";
		String str2 = "朱绍辉";
		String str3 = "bcd";
		String str4 = "cde";
		String str5 = "ABd";
		System.out.println(str1.compareTo(str2));
		System.out.println(str1.compareTo(str3));
		System.out.println(str1.compareTo(str4));
		System.out.println(str1.compareToIgnoreCase(str5));
		
		/*
		 * 2. concat
		 */
		System.out.println(str1.concat(str2).concat(str3));
		
		/*
		 * 3. startsWith /endsWith
		 */
		String str6 = "hello_nihao.doc";
		if(str6.startsWith("hello")){
			System.out.println("hello");
		}
		if(str6.endsWith(".doc")){
			System.out.println(".doc");
		}
		
		/*
		 * 4. equals
		 */
		if(str1.equals(str2)==false){
			System.out.println("not equals");
		}
		
		/*
		 * 5. indexOf/lastIndexOf 
		 * indexOf和lastIndexOf返回的索引都是从字符串的第一个字符开始
		 * indexof和lastIndexOf的第二个参数都是从字符串的第一个字符开始
		 */
		String str7 = "abcdefghk";
		System.out.println(str7.indexOf("d"));
		System.out.println(str7.indexOf('d',1));
		System.out.println(str7.lastIndexOf("d"));
		System.out.println(str7.lastIndexOf('d',2));
		System.out.println(str7.lastIndexOf('d',3));
		
		/*
		 * 6. replace/replaceAll/replaceFirst
		 */
		String str8 = "abacabcdddbaab";
		System.out.println(str8.replace('a', '1'));
		System.out.println(str8.replaceAll("ab", "12"));
		System.out.println(str8.replaceFirst("ab", "12"));
		
		/*
		 * 7. split
		 */
		String str9 = "hello world! nihao";
		String str10 = "abbcbgbbh";//"a","","c","g","","h"
		String[] str9s= str9.split(" ");
		String[] str10s = str10.split("b");
		for( String e: str9s){
			System.out.println(e);
		}
		for( String e: str10s){
			System.out.println(e);
		}
		
		/*
		 * 8.substring
		 */
		String str11="helloworld!";
		System.out.println(str11.substring(2));
		System.out.println(str11.substring(2,4));
		
		/*
		 * 9. trim去掉字符串开头和结尾的所有空格
		 */
		String str12="   str12  ";
		System.out.println(str12.trim());
		
		/*
		 * 10 valueOf
		 */
		int n =12345;
		System.out.println(String.valueOf(n));
	}
}

  

posted @ 2015-08-29 11:03  iken  阅读(103)  评论(0)    收藏  举报