String(문자열)

oh_eol·2022년 2월 20일
0

Algorithm

목록 보기
1/1
post-thumbnail

01. 문자 찾기

import java.util.*;
  
public class Main {
  public int solution(String str, char t) {
  	int answer = 0;
    // 문자열과 문자 모두 대문자로 전환
    str = str.toUpperCase();
    t = Character.toUpperCase(t);
    
    // System.out.print(str);
    
    for(int i = 0; i < str.length(); i++) {
    	if(str.charAt(i) == t) answer++;
    }
    
    return answer;
  }
  
  public static void main(String[] args){
    Main T = new Main();
    Scanner kb = new Scanner(System.in);
    String str=kb.next();
    char c = kb.next().charAt(0);	// charAt(): Stirng 을 index로 접근
    System.out.print(T.solution(str, c));
  }
}
  • 향상된 for 문을 사용
import java.util.*;
  
public class Main {
  public int solution(String str, char t) {
  	int answer = 0;
    // 문자열과 문자 모두 대문자로 전환
    str = str.toUpperCase();
    t = Character.toUpperCase(t);
    
    // System.out.print(str);
    
    // 향상된 for 문에는 배열 형식이 들어와야 하기 때문에
    // str 이 아니라 Stirng 을 배열 형식으로 바꿔주는 toCharArray() 씀.
    for(char x : str.toCharArray()) {
    	if(x == t) answer++;
    }
    
    return answer;
  }
  
  public static void main(String[] args){
    Main T = new Main();
    Scanner kb = new Scanner(System.in);
    String str=kb.next();
    char c = kb.next().charAt(0);	// charAt(): Stirng 을 index로 접근
    System.out.print(T.solution(str, c));
  }
}

02. 대소문자 변환

import java.util.*;
  
public class Main {
  public String solution(String str) {
  	String answer = "";
    // String 배열의 index가 대문자인지 소문자인지 검사 후 answer 에 대/소문자 변환하여 추가
    for(char x : str.toCharArray()) {
    	if(Character.isLowerCase(x)) answer += Character.toUpperCase(x);
      	else answer += Character.toLowerCase(x);
    }
    
    return answer;
  }
  
  public static void main(String[] args){
    Main T = new Main();
    Scanner kb = new Scanner(System.in);
    String str = kb.next();
    System.out.print(T.solution(str));
  }
}
import java.util.*;
  
public class Main {
  public String solution(String str) {
  	String answer = "";
    // String 배열의 index가 대문자인지 소문자인지 검사 후 answer 에 대/소문자 변환하여 추가
    /*for(char x : str.toCharArray()) {
    	if(Character.isLowerCase(x)) answer += Character.toUpperCase(x);
      	else answer += Character.toLowerCase(x);
      }	*/
    // 아스키코드로 해결하는 방법: 65~90=대문자 / 97~122=소문자 -> 32차이 주면 됨
    for(char x : str.toCharArray()) {
    	if(x >= 97 && x <= 122) answer += (char)(x - 32);
        else answer += (char)(x + 32);
    }
    
    return answer;
  }
  
  public static void main(String[] args){
    Main T = new Main();
    Scanner kb = new Scanner(System.in);
    String str = kb.next();
    System.out.print(T.solution(str));
  }
}
profile
공부 중입니다.

0개의 댓글