Light Blue Pointer
본문 바로가기
Coding Test

[프로그래머스][Lv.0]대소문자 바꿔서 출력하기

by Greedy 2023. 10. 30.

문제 주소

https://school.programmers.co.kr/learn/courses/30/lessons/181949

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 설명

영어 알파벳으로 이루어진 문자열 str이 주어집니다. 각 알파벳을 대문자는 소문자로 소문자는 대문자로 변환해서 출력하는 코드를 작성해 보세요.


제한사항

  • 1 ≤ str의 길이 ≤ 20
    • str은 알파벳으로 이루어진 문자열입니다.

입출력 예

입력 #1

aBcDeFg

출력 #1

AbCdEfG

 

제출 코드

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        StringBuffer sb = new StringBuffer();
        for (char ch : a.toCharArray()) {
            if ('a' <= ch && ch <= 'z')
                sb.append((char)(ch - ('a' - 'A')));
            else 
                sb.append((char)(ch + ('a' - 'A')));
        }
        System.out.println(sb.toString());
    }
}

풀이 과정

⭐Java에서 대소문자 바꿔서 출력하는 방법.

String string = "aBcDeF"
string = string.toUpperCase();//ABCDEF
string = string.toLowerCase();//abcdef

⭐equalsIgnoreCase()

→ .equals()랑 똑같은 방법으로 사용, 대소문자는 무시하고 비교해준다

String str1 = "ABC"
String str2 = "abd"
str1.equalsIgnoreCase(str2)//true

예외처리 강의 들을때 matches본거 기억남

⭐String match()

String이 특정 패턴의 문자열을 포함하는지 확인할 수 있음

문자열에 정규표현식(regex)이 일치하는지를 boolean으로 리턴

String str = "my java test";

        //정확히 일치해야 true
        System.out.println( str.matches("java") );  // false
        System.out.println( str.matches("my java Test") );  // false (대/소문자 역시 구분한다.)
        System.out.println( str.matches("my java test") );  // true

        //정규표현식 사용-> 패턴이 맞으면 true
        System.out.println( str.matches(".*java.*") );  // true
        System.out.println( str.matches("(.*)test") );  // true

⭐Java Regular Expressions(Regex,정규표현식)

  • Pattern Class - Defines a pattern (to be used in a search)
  • Matcher Class - Used to search for the pattern
  • PatternSyntaxException Class - Indicates syntax error in a regular expression pattern
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("min", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("mintchoco");
    boolean matchFound = matcher.find();
    if(matchFound) {
      System.out.println("Match found");
    } else {
      System.out.println("Match not found");
    }
  }
}
// Outputs Match found

Match found

  1. Pattern.compile() 메서드로 패턴이 만들어진다.

첫번째 parameter : 어떤 패턴이 찾아지는지 지정(필수)

두번째 parameter : case-insensitive 지정(선택)

  1. matcher() 메서드가 문자열 안에서 패턴을 찾고 결과값을 담 Matcher object를 리턴한다
  2. find() 메서드가 패턴이 발견되면 true를 발견되지 않았으면 false를 반환한다

Flags : flags in the compile() method

  • Pattern.CASE_INSENSITIVE - The case of letters will be ignored when performing a search.
  • Pattern.LITERAL - Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.
  • Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE flag to also ignore the case of letters outside of the English alphabet

Pattern.compile()의 첫번째 parameter

Regular Expression Patterns

[abc] Find one character from the options between the brackets

[^abc] Find one character NOT between the brackets
[0-9] Find one character from the range 0 to 9

Metacharacters : characters with a special meaning

| | | Find a match for any one of the patterns separated by | as in: cat|dog|fish | | --- | --- | | . | Find just one instance of any character | | ^ | Finds a match as the beginning of a string as in: ^Hello | | $ | Finds a match at the end of the string as in: World$ | | \d | Find a digit | | \s | Find a whitespace character | | \b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b | | \uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |

Quantifiers : Quantifiers define quantities

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's
n{x,} Matches any string that contains a sequence of at least X n's

⭐Java String to Char array

// define a string
String vowels = "aeiou";

// create an array of characters 
char[] vowelArray = vowels.toCharArray();

// print vowelArray
System.out.println(Arrays.toString(vowelArray));

일단 해

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        char[] array = a.toCharArray();
        
        for(int i = 0; i<array.length; i++){
            String str = ""+array[i];
            if(str.matches("[a-z]")){
                str = str.toUpperCase();            
            }
            else{
                str = str.toLowerCase();
            }
            array[i]=str.charAt(0);
        }
        System.out.println(array.toString());
    }
}

테스트 1

입력값 〉 "aBcDeFg
"  
기댓값 〉 "AbCdEfG"
실행 결과 〉 실행한 결괏값 [C@b81eda8이 기댓값 AbCdEfG과 다릅니다.
출력 〉 [C@b81eda8

예? 무슨일이 일어나고 있나요?

Q. @는 어떻게 들어갔으며 숫자는 왜 생기고 글자수는 왜 늘어나는거죠?

테스트로 출력해

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        char[] array = a.toCharArray();
        
        for(int i = 0; i<array.length; i++){
            String str = ""+array[i];
            if(str.matches("[a-z]")){
                str = str.toUpperCase(); 
                System.out.println(str);
            }
            else{
                str = str.toLowerCase();
                System.out.println(str);
            }
            array[i]=str.charAt(0);
        }
        System.out.println(array.toString());
    }
}

테스트 1

입력값 〉 "aBcDeFg
"  
기댓값 〉 "AbCdEfG"
실행 결과 〉 실행한 결괏값 A이 기댓값 AbCdEfG과 다릅니다.
출력 〉 AbCdEfG[C@b81eda8

대소문자 바꿀때까지는 제정신이었는데

array[i]=str.charAt(0);

여기서 단단히 잘못되어버림

나는 한글자라 저렇게하면 char될줄 알았는데요…

Q. Java String to Char

일단 그냥 String에다 붙이는게 좋겠음 굳이 다시 array에다 넣었다가 변환할 필요가 없음 필요한 결과값이 String인데

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        char[] array = a.toCharArray();
        String result = "";
        
        for(int i = 0; i<array.length; i++){
            String str = ""+array[i];
            if(str.matches("[a-z]")){
                str = str.toUpperCase(); 
            }
            else{
                str = str.toLowerCase();
            }
            result = result + str;
        }
        System.out.println(result);
    }
}

통과했다

테스트 1

입력값 〉 "aBcDeFg
"  
기댓값 〉 "AbCdEfG"
실행 결과 〉 테스트를 통과하였습니다.
출력 〉 AbCdEfG

다른사람의 풀이

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String answer = "";

        //Stack <Character> stack = new Stack <> ();

        for(Character c : a.toCharArray()){
            if(Character.isUpperCase(c)){
                //stack.push(Character.toLowerCase(c));
                answer += Character.toLowerCase(c);
            }
            else if(Character.isLowerCase(c)){
                //stack.push(Character.toUpperCase(c));
                answer += Character.toUpperCase(c);
            }
        } 
        System.out.println(answer);
    }
}

굳이 matches안 써도 isUpperCase이런게 있네

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        for(int i=0; i<a.length(); i++) {
            char c = a.charAt(i);
            if(Character.isUpperCase(c)) {
                System.out.print((char)(c+32));
            }
            else {
                System.out.print((char)(c-32));
            }
        }
    }
}

이사람은 아스키코드로 32 차이난다는걸 알고 더하고 빼버림

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();

        String answer = "";

        for(int x : a.toCharArray()){
        if(x>=97 && x<=122)answer += (char)(x-32); else answer += (char)(x+32);

}
        System.out.print(answer);
    }
    }

이사람도

이건 좀 신기하다.

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        StringBuffer sb = new StringBuffer();
        for (char ch : a.toCharArray()) {
            if ('a' <= ch && ch <= 'z')
                sb.append((char)(ch - ('a' - 'A')));
            else 
                sb.append((char)(ch + ('a' - 'A')));
        }
        System.out.println(sb.toString());
    }
}