[JAVA] Character duplicate count (substring)


import java.util.*;

//Count the number of times the specified character target is duplicated in the sentence str
public class Main {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
        ArrayList<String> list = new ArrayList<String>();
        
    	//Multiple sum
        int count = 0;
        
        String target = sc.nextLine();
        String str = sc.nextLine();
        
    	//Pack sentences into a list character by character.
        for(int i = 1; i < str.length() + 1; i++){
            list.add(str.substring(i - 1, i));
        }
        
    	//Extract list in order from 0, and if it is equal to the target variable, add 1 to count
        for(int i = 0; i < list.size(); i++) {
            if (target.equals(list.get(i))){
                count++;
            }
        }
        
        System.out.println(count);
        
    }
}

/*
//Writing shorter than substring.
public class Main {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
//split is String[]return it
//Regular expression is included in the argument
//Example:(,)It will be separated by commas.
        String[] str = sc.nextLine().split("");

        int count = 0;
        for (String p : str) {
          if (s.equals(p)) {
            count++;
          }
        }
        System.out.println(count);
    }
}
*/


Recommended Posts

Character duplicate count (substring)
Search for character string B from character string A (duplicate count)
[Java] Character judgment / character string formatting (AOJ11 --character count)