[JAVA]가운데 글자 가져오기

반응형

문제)


getMiddle메소드는 하나의 단어를 입력 받습니다. 단어를 입력 받아서 가운데 글자를 반환하도록 getMiddle메소드를 만들어 보세요. 단어의 길이가 짝수일경우 가운데 두글자를 반환하면 됩니다.
예를들어 입력받은 단어가 power이라면 w를 반환하면 되고, 입력받은 단어가 test라면 es를 반환하면 됩니다.


나의 풀이)


1. length()를 이용하여서 word의 길이를 계산합니다.

2. word가 홀 수라면 /2를 하여서 그 값의 index를 character형태로 추출 후에 string으로 변환합니다.

ex) len = 5

5/2 = 2

0,1,2 -> 3번째 글자 추출


Character -> String Casting


Character.toString(char);


3. word가 짝수라고 하면 substring을 이용하여 앞의 자리 수와 뒤의 자리 수를 짤라준다.

ex)  len = 4

4/2 = 2


앞의 글자 2-1 = 1글자 짤라준다.

뒤의 글자 2+1 = 3글자 짤라준다.


substring()


Stringsubstring(int beginIndex)
Returns a string that is a substring of this string.
Stringsubstring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.



매개변수가 하나면 beginIndex만큼 앞의 자리를 잘라주고,


매개변수가 두개변 앞은 beginIndex 끝은 endIndex만큼 잘라준다.



코드)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class StringExercise{
    String getMiddle(String word){
 
      int len = word.length();
      
      if(len%2==1)
        return Character.toString(word.charAt(len/2));
      else
        return word.substring(len/2-1, len/2+1);
    }
    // 아래는 테스트로 출력해 보기 위한 코드입니다.
    public static void  main(String[] args){
        StringExercise se = new StringExercise();
        System.out.println(se.getMiddle("power"));
    }
}
cs


728x90
반응형