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");
	}
}

 

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기