TIL(2023.08.06)

JAKE·2023년 8월 6일

TIL

목록 보기
19/48
post-thumbnail

🏃‍♂️What I learned

1. split 함수

1) ( )를 기준으로 입력받은 문자 혹은 문자열을 분리시켜 배열로 저장

// e.g.) 
import java.util.Scanner;

public class prac {


	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.print("전화번호 입력(-) 포함 : ");
		String[] phone = sc.next().split("-");   // '-'를 기준으로 분리
		
		for(int i = 0 ; i < phone.length ; i++) {
			System.out.println(phone[i]);
		}
	}
	
}

/* 

결과 값
전화번호 입력(-) 포함 : 010-1111-2222
010
1111
2222


*/

2) ("")면 하나의 문자로 분리


2. toCharArray 함수

1) 문자열을 하나의 문자로 분리시켜 배열에 저장하는 함수

.split(""); 과 결과는 동일

// e.g.)
import java.util.Scanner;

public class prac {

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

		System.out.print("전화번호 입력(-) 포함 : ");
		String phone2 = sc.nextLine();
		char[] arr = phone2.toCharArray(); 
		
		for(int i = 0 ; i < phone2.length() ; i++) {
			System.out.println(arr[i]);
		}
		
		
	}
    
/* 

결과 값
전화번호 입력(-) 포함 : 010-1111-2222
0
1
0
-
1
1
1
1
-
2
2
2
2

*/
    

0개의 댓글