728x90
s.charAt() : String으로 저장된 문자열 중에서 한 글자만 선택해서 char형으로 변환
1. for 문
public class chp4_5_3_for {
public static void main(String[] args) {
int i = 0;
String s = new String("string");
char c='r'; int sw=0;
for(i=0; s.charAt(i) != '\0'; i++) {
if ( c == s.charAt(i)) {
sw=1;
System.out.println("Position of " + c + " = " + (i++));
break;
}
}
if (sw == 0)
System.out.println("Not found");
}
}
2. while 문
public class ExerciseCh4_5_3 {
public static void main(String[] args) {
int i = 0;
String s = new String("string");
char c='r'; int sw=0;
while(s.charAt(i) != '\0')
if ( c == s.charAt(i)) {
sw=1;
System.out.println("Position of " + c + " = " + (i++));
break;
} else i++;
if (sw == 0)
System.out.println("Not found");
}
}
3. do while 문
public class chp4_5_3_do_while {
public static void main(String[] args) {
int i = 0;
String s = new String("string");
char c='r'; int sw=0;
do {
if ( c == s.charAt(i)) {
sw=1;
System.out.println("Position of " + c + " = " + (i++));
break;
} else i++;
} while(s.charAt(i) != '\0');
if (sw == 0)
System.out.println("Not found");
}
}
반응형
'전.java' 카테고리의 다른 글
윤년인지 판별 (isDigit() 함수 이용하여 입력 받음) (0) | 2021.01.31 |
---|---|
char 형 배열 (개선된 for 문) (0) | 2021.01.31 |
char 형 배열 (for, while, do while 문) (0) | 2021.01.31 |
팩토리얼 (while, do while 문) (0) | 2021.01.31 |
연도를 읽어 윤년인지를 판별하는 프로그램 (0) | 2021.01.31 |