码迷,mamicode.com
首页 > 编程语言 > 详细

java中如何知道一个字符串中有多少个字,把每个字打印出来,举例

时间:2018-09-22 18:31:37      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:如何   where   int   lse   需要   字符   str   this   main   

  (视频下载) (全部书籍)

9.6 About string,"I am a teacher",这个字符串中有多少个字,且分别把每个字打印出来。

 

/*本题的思路就是,当我有一个字符串,我需要一个一个字符的处理,当下一个字符是个空格的时候,我就知道前面已 经构成了一个完整的字,把它输出出来就好了。如果发现下一个字符不是一个空格的话,我就把这个字符,加到另一个字符串中,逐渐积累那个字符串成为一个完整 的字。*/

public class Test {
    static int amount_space = 0; //此变量用来记录空格的数量。the variable named amount_space is used to count the number of the space.
    static int flag_Pro = 0; //此变量用来记录现在处理到大字符串中哪一个字符了。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,取出的字符是个空格,就执行这段程序。
                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);如果不是一个空格,就加到outputword中。
                outputword = outputword + newstring.substring(i, i + 1);
                flag_Pro++;
            }
        }

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

结果:

I
am
a
teacher
共有3个空格
共有4个字


详情请见:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner1_web.html#9.6

java中如何知道一个字符串中有多少个字,把每个字打印出来,举例

标签:如何   where   int   lse   需要   字符   str   this   main   

原文地址:https://www.cnblogs.com/mark-to-win/p/9690462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!