字符串中各类字符的总和汇总 字符串中子串个数查询实现

各类字符总和

import java.util.Scanner;

public class StringTest
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
       
        System.out.println("请输入一行字符串:");
        String s = sc.nextLine();

        int big=0,small=0,space=0,other=0;
        for(int i=0;i<s.length();i++)
        {
            char c = s.charAt(i);
            if(c>='a' && c<='z')
                small++;
            if(c>='A' && c<='Z')
                big++;
            if(c == 32)
                space++;
            else
                  other++;
        }
        System.out.println("小写字母为:" + small + "  大写字母为:"+ big + "  空格为:" + space + "  其他字符为" + other);
    }
}

 

子串个数查询:

 

使用subString

import java.util.*;


public class StringTest2
{

    public static void main(String args[])
    {

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一行字符串:");
        String s = sc.nextLine();
        System.out.println("请输入要查询个数的字符串");
        String aim= sc.nextLine();
        int number = 0;
        for(int i = 0;i<=s.length()-aim.length();i++)
        {
            if(s.substring(i,i+aim.length()).equals(aim))
            {
                  number++;
                  i = i + aim.length() - 1;
             }
        }
        System.out.println("字符串"+aim+"的个数为"+number+"!!!");
    }
}

 

 

使用indexOf:

import java.util.*;
public class StringTest3
{
      public static void main(String args[])
      {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一行字符串:");
        String s = sc.nextLine();
        System.out.println("请输入要查询个数的字符串");
        String aim= sc.nextLine();
        int number=0;
        int start = 0;
        while(s.indexOf(aim,start)>=0 && start < s.length())
        {
              number++;
              start = s.indexOf(aim,start) + aim.length();
        }
        System.out.println("出现的次数为" + number + "!");

      }
}

posted on 2010-10-16 16:23  境_  阅读(443)  评论(0编辑  收藏  举报

导航