字符串基礎學習筆記(三)

1、其他常用功能


①分隔字符串

public class StringDemo1 {
	
	public static void main(String[] args) {
		String str = "3000-3999-uuu-999-kkk-2323";
		System.out.println(str);
		//分隔字符串,如果是特殊字符需要轉義"\\"
		String[] strs = str.split("-");
		for(int i = 0; i < strs.length; i++){
			String str1 = strs[i];
			System.out.println(str1 );
		}		
	}	
}

②字符或者字符串的替代

public class StringDemo2 {
	
	public static void main(String[] args) {
		String str = "3000-3999-uuu-999-kkk-2323";
		//字符串中的單個字符替換,第一個參數是被替換的字符,第二個參數是新的字符
		String str1 = str.replace('-', '#');
		System.out.println(str1);
		//字符串中的字符串替換第一個參數是被替換的字符串,第二個參數是新的字符串
		String str2 = str.replace("999", "888");
		System.out.println(str2);
	}	
}

③去掉字符串兩邊的空格及倒敘索引

public class StringDemo3 {
	
	public static void main(String[] args) {
		String str3 = "     txjava ";
		//去掉字符串兩邊的空格
		String str4 = str3.trim();
		System.out.println("---"+str4+"---");
		//從後面開始查找第一次出現的a
		int index = str3.lastIndexOf("a");
		System.out.println(index);
		//在給定的索引的前面倒序查找第一次出現子字符串的索引
		int index1 = str3.lastIndexOf("a", 9);
		System.out.println(index1);
	}	
}

2、練習例子:找出下面字符串中ffx的數量

public class StringDemo4 {
	public static void main(String[] args) {
		String str = "helloffxwoshiainideffxainiyiwannianffxhahaha";
		System.out.println(str);
		int count = 0;
		//獲得li的第一次出現的索引(計時器的初始化)
		int index = str.indexOf("ffx");
		//循環字符串
		while(index != -1){
			count++;
			//後面指定地方需要將ffx本身去掉
			index = str.indexOf("ffx", index+3);
		}
		System.out.println("ffx的出現次數是:"+count);
	}
}

3、小結

①在分隔字符串的式子中,如果是特殊字符串(如:¥ * .)等需要用"\\"進行轉義;

②在以後字符串使用中必須先將字符串進行空格處理;

③正索引的倒敘索引都可以指定索引,但要注意不要溢出;

④字符串出現在實例中時應該先判斷是否是空字符串。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章