JAVA 문제풀이

배열 실습문제.4

Rocomi 2024. 6. 21. 11:15

문자열을 입력 받아 문자 하나하나를 배열에 넣고 검색할 문자가 문자열에 몇 개

들어가 있는지 개수와 몇 번째 인덱스에 위치하는지 인덱스를 출력하세요.

ex.

문자열 : application

문자 : i

application에 i가 존재하는 위치(인덱스) : 4 8

i 개수 : 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.kh.practice.array;
 
import java.util.Scanner;
 
public class ArrayPractice {
 
    public void practice5() {
        Scanner sc = new Scanner(System.in);
 
        System.out.print("문자열 : ");
        String str1 = sc.nextLine();
 
        System.out.print("문자 : ");
        String str2 = sc.nextLine();
        char[] ch = new char[str1.length()];
 
        for (int i = 0; i < str1.length(); i++) {
            ch[i] = str1.charAt(i);
        }
        System.out.printf("%s에 %s가 존재하는 위치(인덱스) :", str1, str2);
 
        int j = 0;
 
        for (int i = 0; i < str1.length(); i++) {
            if (ch[i] == str2.charAt(0)) {
                System.out.print(" ");
                System.out.print(i);
                j++;
            } else if (i == str1.length() - 1) {
                System.out.print("\n");
            }
        }
        System.out.print(str2 + " 개수 : " + j);
    }
 
    
}
cs