문제 설명

문장 sentence에서 word가 몇 번째 단어와 일치하는지를 출력하는 프로그램을 구현하세요.

sentence에서 단어의 구분은 공백(" ")으로 구분하며, 단어는 0번째부터 시작합니다.

단, word가 sentence에 포함되지 않을 경우, -1를 출력하세요.


입력 형식

· sentence : 단어가 공백으로 구분된 문자열

· word : 찾고자 하는 단어 문자열


출력 형식

· word가 sentence에 몇 번째 단어와 일치하는지 정수로 반환


제약 사항

· 0 <= sentence.length <= 1000

· 0 <= word.length <= 1000

· sentence[i], word[i]는 알파벳 대소문자입니다.


입출력 형식

· 예시1

  · 입력

      · sentence = "Hello every world"

      · word = "every"

  · 출력 : 1

  · 설명 : every는 두 번째 단어이므로, 답은 1이다. 0번째부터 센다는 것을 고려

 

· 예시2

  · 입력

      · sentence = "Hello every world"

      · word = "ever"

  · 출력 : -1

  · 설명 : ever라는 단어는 sentence에 포함되어 있지 않으므로 -1이 출력이 된다.


정답 코드

class Solution {
    public int solution(String sentence, String word) {
        if (word.equals("")) {
            return -1;
        }

        String[] words = sentence.split(" ");

        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word)) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        String sentence = "Hello every world";
        String word = "every";
        String word2 = "ever";
        System.out.println(st.solution(sentence, word));
        System.out.println(st.solution(sentence, word2));
    }
}