JAVA

210804_charAt,substring,equal

요옫 2021. 8. 4. 11:40

charAt

// charAt(숫자) - 숫자는 index번호를 의미

 

Scanner sc=new Scanner(System.in);

 

char fruit;

 

System.out.println("과일 알파벳 1글자를 입력하세요");

fruit=sc.nextLine().charAt(0);

//입력한 문자열의 첫글자만 가져오는 걸 의미

 

System.out.println("fruit= "+fruit);

 

//조건문을 스위치로 만들기

switch (fruit) {

case 'a':  //char이기에 ''

case 'A':

System.out.println("Apple");

break;

case 'b':  

case 'B':

System.out.println("Banana");

break;

case 'o':  

case 'O':

System.out.println("Orange");

break;

case 'm':  

case 'M':

System.out.println("Mango");

break;

 

default:

System.out.println("찾는 과일이 없습니다");

 

//결과

과일 알파벳 1글자를 입력하세요

g

fruit= g

찾는 과일이 없습니다

 

------------------

 

(예제)

//charAt()을 통해 한글자 가져오기

 

String jumin="800112-3260711";

    char seventh=jumin.charAt(7);

//index값으로 가져오면 첫글자인 8이 0번째, 0이 1번째~

 

//if,switch문을 이용하여

//2000년생 이후 남자입니다

 

     

switch (seventh) {

case '3':

System.out.println("2000년생 이후 남자입니다");

break;

case '4':

System.out.println("2000년생 이후 여자입니다");

break;

 

default:

System.out.println("2000년생이 아닙니다");

}

 

//결과

2000년생 이후 남자입니다

 

--------------------

 

substring

//chatAt(숫자):1글자

//substring():원하는 대로 여러 글자 가능

 

String str="나는 쌍용 강남에서 자바를 공부중입니다";

 

char ch=str.charAt(3);  //공백도 index번호에 포

    String word1=str.substring(3);  //문자열이니까 string이며 index번호를 시작으로 끝까지 출력됨

 

    //강남에서  를 출력하고 싶다면 substring beginindex/endindex

    String word2=str.substring(6, 10);  //뒷번호는 내가 원하는 번호+1

   

    int i=str.length();  //총글자 수를 알고 싶을 때

   

System.out.println(ch);  //쌍

System.out.println(word1);  //쌍용 강남에서 자바를 공부중입니다 

System.out.println(word2);  //강남에

System.out.println(i);  //21(공백포함)

 

--------------------

 

equals

//문자열 비교는 관계연산자로 하면 안 된다

//equals라는 매소드를 사용해야 함

 

Scanner sc=new Scanner(System.in);

 

String msg;

 

System.out.println("영어 단어를 입력하세요");

System.out.println("ex)hello,happy,angel,rose");

msg=sc.nextLine();

 

System.out.println("입력한 문자열은 "+msg+" 입니다");

 

//문자열을 연산자로 비교하면 주소비교를 하게 됨

//값 비교를 하려면 equal이라는 매소드 사용

 

if(msg.equals("angel"))  //문자열을 비교해서 같으면 true

//equals는 다 같아야 하며 equalsignore는 대소문자 틀리는 것까지는 가능

System.out.println("천사입니다");

else if(msg.equals("hello"))

System.out.println("안녕하세요");

else if(msg.equals("happy"))

System.out.println("행복합니다");

else if(msg.equals("rose"))

System.out.println("장미");

else 

System.out.println("찾는 단어가 없습니다");

 

//결과

영어 단어를 입력하세요

ex)hello,happy,angel,rose

rose

입력한 문자열은 rose 입니다

장미

 

'JAVA' 카테고리의 다른 글

210804_for  (0) 2021.08.04
210804_for,while,break,continue(정의)  (0) 2021.08.04
210804_조건문Switch  (0) 2021.08.04
210803_조건문if  (0) 2021.08.04
210803_연산자  (0) 2021.08.03