如題,下列寫出列出字串每個字元的程式碼,還有使用字串的 substring 功能的程式碼。

這邊的重點除了兩者的程式用法之外,最重要的是兩者的index不同,必須要特別注意。

假設我們有一個字串 abcd。

這個字串在字元數就是4個,但是substring的範圍則是0~4,index是5個,因為substring是看字元與字元的間距,並且包含頭尾兩個。

所以是 (4-1)+2=5。

範例程式碼如下:

 

public static void main(String args[])
	{
		String temp = "一二三班";
		System.out.println("列出上述字串的每個字元: ");
		//character index有4個
		for(int i=0;i<temp.length();i++)
			System.out.println("字元index: "+i+" 字元為: "+temp.charAt(i));
		
		//substring index有5個,在此的index主要代表字元與字元之間的空格
		System.out.println("列出上述字串的子字串(一二、三班): ");
		System.out.println("一二: "+temp.substring(0, 2));
		System.out.println("三班: "+temp.substring(2, 4));
	}
Output:
列出上述字串的每個字元: 
字元index: 0 字元為: 一
字元index: 1 字元為: 二
字元index: 2 字元為: 三
字元index: 3 字元為: 班
列出上述字串的子字串(一二、三班): 
一二: 一二
三班: 三班
arrow
arrow
    全站熱搜

    葛瑞斯肯 發表在 痞客邦 留言(0) 人氣()