Java50道经典习题-程序49 子串出现的个数

题目:计算首末不含空格各个子串之间只含一个空格的字符串中子串出现的次数
分析:例如输入的字符串为"I come from County DingYuan Province AnHui."
空格隔断的即为字符子串,所以上述字符串的子串个数有7个

 1 public class Prog49{
 2     public static void main(String[] args){
 3         String str="I come from County DingYuan Province AnHui.";
 4         int count=0;
 5         char[] ch=str.toCharArray();//将字符串转换成字符数组
 6         for(int i=0;i<ch.length;i++) {
 7             if(ch[i]==' ')//计算字符串中的空格个数
 8                 count++;
 9         }
10         count++;//字符串中子串的个数=空格数+1
11         System.out.println("共有"+count+"个字符子串");
12     }
13 }
14 /*运行结果
15 共有7个字符子串
16 */

 

posted @ 2019-04-30 15:49  parkour高手  阅读(315)  评论(0编辑  收藏  举报