输入一个字符串,再输入要查找的字符,判断该字符在该字符串中出现的次数

如题

package com.mxy.HomeWork;

import java.util.Scanner;

/**
 * 1: 输入一个字符串,再输入要查找的字符,判断该字符在该字符串中出现的次数
 *
 * @author MXHstrat
 * @create 2021 - 11 - 03  20:16
 */
public class Test01 {
    public static void main(String[] args) {

        System.out.print("请输入第一串字符:");
        String s1 = new Scanner(System.in).next();
        System.out.print("请输入第二串字符:");
        String s2 = new Scanner(System.in).next();
        Test01 t1 = new Test01();
        int counter = t1.counter(s1, s2);
        System.out.println("找到的次数为 = " + counter);
    }

    public int counter(String inputs, String word) {
        int inputLength = inputs.length();
        int wordLength = word.length();
        int index = 0;
        int count = 0;

        if (inputLength >= wordLength) {
            while ((index = inputs.indexOf(word, index)) != -1) {
                index += wordLength;
                count++;
            }
            return count;
        } else
            return 0;
    }
}

你可能感兴趣的:(笔记,java-ee)