java中如何知道一個(gè)字符串中有多少個(gè)字,把每個(gè)字打印出來

9.6 About string,"I am a teacher",這個(gè)字符串中有多少個(gè)字,且分別把每個(gè)字打印出來。/*本題的思路就是,當(dāng)我有一個(gè)字符串,我需要一個(gè)一個(gè)字符的處理,當(dāng)下一個(gè)字符是個(gè)空格的時(shí)候,我就知道前面已經(jīng)構(gòu)成了一個(gè)完整的字,把它輸出出來就好了。如果發(fā)現(xiàn)下一個(gè)字符不是一個(gè)空格的話,我就把這個(gè)字符,加到另一個(gè)字符串中,逐漸積累那個(gè)字符串成為一個(gè)完整的字。*/
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。





public class Test {
    static int amount_space = 0; //此變量用來記錄空格的數(shù)量。the variable named amount_space is used to count the number of the space.
    static int flag_Pro = 0; //此變量用來記錄現(xiàn)在處理到大字符串中哪一個(gè)字符了。this pointer is used to remember the position where we look over.
    static String newstring = "I am a teacher";
    public static void main(String[] args) {
        String outputword = "";
        for (int i = flag_Pro; i < newstring.length(); i++) {
            if (newstring.substring(i, i + 1).equals(" ")) { //假如newstring.substring(i, i + 1)馬克-to-win,取出的字符是個(gè)空格,就執(zhí)行這段程序。
                System.out.println(outputword);
                outputword = "";
                amount_space++;
                flag_Pro++; // and next time we will start at a new position
            } else {//newstring.substring(i, i + 1);如果不是一個(gè)空格,就加到outputword中。
                outputword = outputword + newstring.substring(i, i + 1);
                flag_Pro++;
            }
        }

        System.out.println(outputword);
        outputword = "";System.out.println("共有"+amount_space+"個(gè)空格");
        System.out.println("共有"+(++amount_space)+"個(gè)字");
    }
}

結(jié)果:
I
am
a
teacher
共有3個(gè)空格
共有4個(gè)字