Java charat 예제 - Java charat yeje

charAt 함수란?
String 타입의 데이터(문자열)에서 특정 문자를 char 타입으로 변환할 때 사용하는 함수이다.

String sample = "abc";
char target = sample.charAt(0);

위처럼 String 변수에서 사용할 수 있으며,
charAt(i)
i 자리에는 int 형 변수를 넣어서 원하는 위치의 문자를 가져올 수 있다.

사용법

public static void main(String[] args) {
	    String example = "안녕하세요";
        
	    char target1;
	    char target2;
	    char target3;
	    
	    target1 = example.charAt(0);
	    target2 = example.charAt(1);
	    target3 = example.charAt(2);
	    
	    System.out.println(target1);
	    System.out.println(target2);
	    System.out.println(target3);
	}

결과

example의 문자열인 "안녕하세요" 기준으로

target1은 0번째 인덱스의 "안"을 출력

target2은 1번째 인덱스의 "녕"을 출력

target3은 2번째 인덱스의 "하"을 출력한다.

subStirng 함수

문자의 시작번호 또는 문자의 시작과 끝을 지정할 수 있다.

사용법은 다음과 같다.

public static void main(String[] args) {
	    String example = "안녕하세요";
	    
	    String target1 = example.substring(0);
	    String target2 = example.substring(1, 4);
	    String target3 = example.substring(4);
	    
	    
	    System.out.println(target1);
	    System.out.println(target2);
	    System.out.println(target3);
}

exapmle = "안녕하세요" 기준으로

target1는 example의 0번째 인덱스부터 시작해서 "안녕하세요" 출력

target2는 example의 1번째 인덱스부터 시작해서 4번째 인덱스까지 "녕하세" 출력

target3는 example의 4번째 인덱스부터 시작해서 "요" 출력

In Java, the index of Strings starts from 0, not 1. That's why chartAt(0) returns the first character. Similarly,

string.charAt(int index)
0 and
string.charAt(int index)
1 return the sixth and seventh character respectively.


If you need to find the index of the first occurrence of the specified character, use the Java String indexOf() method.

어떤 프로그램이건 문자열은 데이터로서 아주 많이 사용되므로, 그 중요성은 여러 번 강조해도 부족합니다.
저번 자바 문자열 포스팅에서 자바 String 메소드 표를 보았었는데,
이 String 메소드들만 잘 쓸 줄 알아도, 자바에서 문자열을 다루는 데 매우 편리합니다.
이번 포스팅에서는 여러 가지 자바 String 메소드들을 실제로 사용해 봅시다.
어느 정도 비슷한 성질을 가진 메소드들 끼리 묶어 놓았습니다.
기본적인 설명은 예시 코드 안의 주석에 있습니다.

( 아래 포스팅에서 자주 쓰이는 자바 String 메소드를 한 눈에 볼 수 있습니다. )

The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.

Syntax

The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index position in a string. It throws StringIndexOutOfBoundsException if the index is a negative value or greater than this string length.

Specified by

CharSequence interface, located inside java.lang package.

Internal implementation

Java String charAt() Method Examples

Let's see Java program related to string in which we will use charAt() method that perform some operation on the give string.

FileName: CharAtExample.java

Test it Now

Output:

Let's see the example of the charAt() method where we are passing a greater index value. In such a case, it throws StringIndexOutOfBoundsException at run time.

FileName: CharAtExample.java

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

Accessing First and Last Character by Using the charAt() Method

Let's see a simple example where we are accessing first and last character from the provided string.

FileName: CharAtExample3.java

Output:

Character at 0 index is: W
Character at last index is: l

Let's see an example where we are counting the number of vowels present in a string with the help of the charAt() method.

The Java String charAt(int index) method returns the character at the specified index in a string. The index value that we pass in this method should be between 0 and (length of string-1). For example: s.charAt(0) would return the first character of the string represented by instance s. Java String charAt method throws IndexOutOfBoundsException, if the index value passed in the charAt() method is less than zero or greater than or equal to the length of the string (index<0|| index>=length()).

Java String charAt() Method example

Lets take an example to understand the use of charAt() method. In this example we have a string and we are printing the 1st, 6th, 12th and 21st character of the string using charAt() method.

public class CharAtExample {
   public static void main(String args[]) {
	String str = "Welcome to string handling tutorial";
	//This will return the first char of the string
	char ch1 = str.charAt(0);
		
	//This will return the 6th char of the string
	char ch2 = str.charAt(5);
		
	//This will return the 12th char of the string
	char ch3 = str.charAt(11);
		
	//This will return the 21st char of the string
	char ch4 = str.charAt(20);
		
	System.out.println("Character at 0 index is: "+ch1);
	System.out.println("Character at 5th index is: "+ch2);
	System.out.println("Character at 11th index is: "+ch3);
	System.out.println("Character at 20th index is: "+ch4);
   }
}

Output:

Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

IndexOutOfBoundsException while using charAt() method

When we pass negative index or the index which is greater than length()-1 then the charAt() method throws IndexOutOfBoundsException. In the following example we are passing negative index in the charAt() method, lets see what we get in the output.

public class JavaExample {
   public static void main(String args[]) {
	String str = "BeginnersBook";
	//negative index, method would throw exception
	char ch = str.charAt(-1);
	System.out.println(ch);
   }
}

Output:

Java charat 예제 - Java charat yeje

Java String charAt() example to print all characters of string

To print all the characters of a string, we are running a for loop from 0 to length of string – 1 and displaying the character at each iteration of the loop using the charAt() method.

public class JavaExample {
   public static void main(String args[]) {
	String str = "BeginnersBook";
	for(int i=0; i<=str.length()-1; i++) {
		System.out.println(str.charAt(i));
	}
   }
}

Output:

B
e
g
i
n
n
e
r
s
B
o
o
k

Java String charAt() example to count the occurrence of a character

In this example, we will use the charAt() method to count the occurrence of a particular character in the given string. Here we have a string and we are counting the occurrence of character ‘B’ in the string.