본문 바로가기

ETC/복습

[복습_JAVA] 16

실습(문자 배열)

1. length()

public class StringTest { 
	
	public static void main(String[] args) {

		String data = "ABC";  // 3칸짜리 문자 배열

		System.out.println(data.length());

		
	}
}
 
결과

 

 

 

2. charAt()

public class StringTest { 
	
	public static void main(String[] args) {

		String data = "ABC";  // 3칸짜리 문자 배열

		System.out.println(data.charAt(1));

		
	}
}

 

결과

 

 

 

3. split()

public class StringTest { 
	
	public static void main(String[] args) {

		String scores = "10, 20, 30";

		// scores.split(",")는 3칸 문자열 배열의 시작 주소이다.
		System.out.println(scores.split(", ")[1]);

		
	}
}

 

결과

 

 

 

※ 문자열 배열

public class StringTest { 
	
	public static void main(String[] args) {
		
		String scores = "10, 20, 30";
		String[] arScore = {"10", "20", "30"};

		System.out.println(arScore[1]);  // scores.split(",")[1]과 같다

		// arScore라는 문자열 배열에 위 배열의 시작주소를 대입한다.
		// 자료형이 서로 같기 때문에 가능하다.
		arScore = scores.split(",");  
		
	}
}

 

결과

 

 

 

 

실습(문자열 배열)

1. 사용자에게 입력받은 문자열 중 소문자는 모두 대문자로, 대문자는 모두 소문자로 변경한다.(알파벳이 아닌 문자들은 그대로 유지한다.)

import java.util.Scanner;
 
public class ArTask2 {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		// 아래에서 대입을 한다면 null로 초기화
		String str = null;
		
		// 아래에서 연결을 한다면 ""로 초기화
		String result = "";  // 대문자 또는 소문자로 변경된 값을 담아줄 변수
		
		System.out.print("문자열 : ");
		str = sc.next();

		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);

			if(c >= 65 && c <= 90) {
				result += (char)(c + 32);
			} else if(c >= 97 && c <= 122) {
				result += (char)(c - 32);
			} else {
				result += c; 
			}
			
		}
		System.out.println("변경된 문자열 : " + result);
		
	}
}

 

결과

 

 

 

2. 입력한 정수를 한글로 변경한다.

※ 참고

입력 예) 1024 
출력 예) 일공이사

//1회차
// 1024 % 10 == 4
// 1024 / 10 == 102

//2회차
//102 % 10 == 2
//102 / 10 == 10

//3회차
//10 % 10 == 0
//10 / 10 == 1

//4회차
//1 % 10 == 1
//1 / 10 == 0

// 몫이 0일 때까지 반복

 

 

- 코드

import java.util.Scanner;

public class ArTask2 {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		String hangle = "공일이삼사오육칠팔구";
		int num = 0; 
		String result = "";
		
		System.out.print("정수 : ");
		num = sc.nextInt();
		
		while(num != 0) {
			result = hangle.charAt(num % 10) + result;  // hangle에서 나머지 값과 같은 인덱스에 들어있는 값을 가져온다.
			num /= 10;
		}

		System.out.println(result);
		
	}
}

 

결과

 

 

 

'ETC > 복습' 카테고리의 다른 글

[복습_JAVA] 18  (0) 2022.08.28
[복습_JAVA] 17  (0) 2022.08.27
[복습_JAVA] 15  (0) 2022.08.22
[복습_JAVA] 14  (0) 2022.08.21
[복습_JAVA] 13  (0) 2022.08.20