[Java] Character duplicate count (substring)

less than 1 minute read

```java

import java.util.*;

// Count the number of times the specified character target overlaps in the text str public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList list = new ArrayList();

// Sum of duplicates
    int count = 0;
    
    String target = sc.nextLine();
    String str = sc.nextLine();
    
// Pack sentences one by one into list.
    for(int i = 1; i <str.length() + 1; i++){
        list.add(str.substring(i-1, i));
    }
    
//Extract list from number 0 in order and add 1 to count if it is equal to the target variable
    for(int i = 0; i <list.size(); i++) {
        if (target.equals(list.get(i))){
            count++;
        }
    }
    
    System.out.println(count);
    
} }

/* // Shorter than substring public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); //split returns a String[] // Regular expression is entered in the argument // Example: (,) 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);
} } */ 

Tags:

Updated: