可變字符串基礎學習筆記(二)和隨機數學習筆記

一、可變字符串

1、插入


public class StringBufferDemo3 {
	
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer("helloworld");
		//在指定的索引位置插入字符串,注意不要出現字符串的索引越界的問題
		sb.insert(3, "KKK");
		
		char [] cs = {'a','b','c','d'};
		//第一個參數要插入的索引位置,第二個參數要插入的字符數組,第三參數是數組的起始索引,第四個參數是要插入的長度
		sb.insert(3, cs, 1, 3);
		System.out.println(sb);	
	}
}

2、刪除


public class StringBufferDemo4 {
	
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer("hello");
		第一個參數刪除的開始索引,第二個參數是刪除的結束索引,刪除的包含開始索引,不包含結束的索引
		//sb.delete(2, 3);
		//如果清空字符串
		sb.delete(0, sb.length());
		//刪除指定的索引的字符,很少用
		sb.deleteCharAt(1);
		System.out.println(sb);
	
	}
}

3、替換於反轉


public class StringBufferDemo5 {
	
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer("hllelloworlld");
		//第一個參數是替換的開始索引,第二個參數是替換結束索引,第三個參數是替換的字符串
		sb.replace(2, 4, "dddd");
		//字符串的反轉
		sb.reverse();
		System.out.println(sb);
		//獲得倒數第一次出現的字符串
		int lastIndex = sb.lastIndexOf("ll");
		System.out.println(lastIndex);
		//獲得從指定的索引開始向前數,找到倒數第一次出現的字符串的索引
		int lastIndex1 = sb.lastIndexOf("ll", 5);
		System.out.println(lastIndex1);
	}
}

二、Random隨機數產生類

1、Random的構造器


2、Random常用方法


import java.util.Random;

public class RandomDemo1 {
	
	public static void main(String[] args) {
		printRandom();
	}
	
	public static void printRandom(){
		//創建隨機數的對象
		Random r = new Random();
		//獲得隨機的整數
		/*int intVal = r.nextInt();
		System.out.println(intVal);*/
		for(int i = 0; i < 10; i++){
			//獲得指定區間的隨機數
			int intVal = r.nextInt(10);
			//boolean bVal = r.nextBoolean();
			//float fVal = r.nextFloat();
			System.out.println(intVal);
		}
	}
	
	public static void printRandomSeed(){
		//創建隨機數的對象
		Random r = new Random(998l);
		//獲得隨機的整數
		/*int intVal = r.nextInt();
		System.out.println(intVal);*/
		for(int i = 0; i < 10; i++){
			//獲得指定區間的隨機數
			int intVal = r.nextInt(1000);
			//boolean bVal = r.nextBoolean();
			//float fVal = r.nextFloat();
			System.out.println(intVal);
		}
	}

}

三、小結

1、可變字符串在指定的索引位置插入字符串時注意不要出現字符串的索引越界問題;

2、可變字符串刪除方法中,刪除包含開始索引值,但是不包含結束索引值;

3、隨機數Random第二個構造器中,使用一個long種子創建一個新的隨機數,這個隨機數是固定的,可以用於密碼使用。


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