0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

文字の重複カウント(substring)

Last updated at Posted at 2020-07-09

import java.util.*;

//文章strのなかで指定文字targetの重複する回数をカウントする
public class Main {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
        ArrayList<String> list = new ArrayList<String>();
        
    	//重複数の合計
        int count = 0;
        
        String target = sc.nextLine();
        String str = sc.nextLine();
        
    	//文を一文字ずつlistに詰める。
        for(int i = 1; i < str.length() + 1; i++){
            list.add(str.substring(i - 1, i));
        }
        
    	//listを0番から順番に抜出しtarget変数と等しければcountにプラス1
        for(int i = 0; i < list.size(); i++) {
            if (target.equals(list.get(i))){
                count++;
            }
        }
        
        System.out.println(count);
        
    }
}

/*
//substringより短い書き方。
public class Main {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
//splitはString[]を返す
//引数に正規表現が入る
//例:(,)カンマごとに区切ることになる。
        String[] str = sc.nextLine().split("");

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?