JAVA/명령어
Java - 명령어 - 문자열 특정값 가져오기
상상날개
2022. 9. 16. 19:13
1. charAt( )
- 반환하는 조건에 정수 인덱스 값을 매개 변수로 사용한다
- 해당 인덱스에 있는 문자를 반환한다
- String 클래스 메서드와 해당 반환 유형은 char 값이다
public class String_getTextOfLocation {
//charAt() 사용하여 문자 출력
public static Character getFirstCharacter(String str){
if(str == null || str.length() == 0) { //문자열이 null이거나 문자열 길이가 0이면
return null; //null을 반환
} else {
return (Character) str.charAt(0); //그렇지 않으면 문자열의 0번째 문자를 반환
}
}
public static void main(String[] args)
{
String str = "Hello welcome to develop world!!";
System.out.println("문자열 : " + str);
System.out.print("문자열에 첫번째 문자는 : " + getFirstCharacter(str));
}
}
문자열 : Hello welcome to develop world!!
문자열에 첫번째 문자는 : H
2. substring( )
- startIdx에서 시작하는 하위 문자열부터 나머지 모든 문자를 반환한다
- startIdx, endIdx를 전달하면 startIdx에서 시작하여 endIdx-1번째 문자까지 반환한다
public String substring(int startIdx)
public String substring(int startIdx, int endIdx)
public class String_getTextOfLocation_substring {
public static void main(String[] args){
String str = "Hello welcome to develop world!!";
//01234567890123456789012345678901
System.out.println("문자열 : " + str);
System.out.println("시작점 index(3): " + str.substring(3)); //4번째 문자부터 전체 반환
System.out.println("index(2)부터 index(6)까지의 문자 : " + str.substring(2, 7)); //3번째 문자부터 6번째 앞 문자까지
System.out.println("index(3)부터 index(7)까지의 문자 : " + str.substring(3, 8)); //3번째 문자부터 8번째 앞 문자까지
System.out.print("문자열에 첫번째 문자는 : " + getFirstCharacter(str)); //첫번째 문자열 가져오기
}
public static String getFirstCharacter(String str)
{
if(str == null || str.length() == 0) //빈 문자열일 경우의 조건
return null;
else
return str.substring(0, 1);
}
}
문자열 : Hello welcome to develop world!!
시작점 index(3): lo welcome to develop world!!
index(2)부터 index(6)까지의 문자 : llo w
index(3)부터 index(7)까지의 문자 : lo we
문자열에 첫번째 문자는 : H
3. toCharArray( )
- index 값을 사용하여 배열의 요소에 액세스할 수 있다
- 문자열을 char 데이터 유형의 배열로 변환할 수 있다면 index를 사용하여 모든 요소를 가져올 수 있다
- 인덱스 0을 통해 첫 번째 문자를 가져올 수 있다
- toCharArray() 메서드를 사용하여 문자열을 문자 배열로 변환한다
public class String_getTextOfLocation_toCharArray {
public static Character getFirstCharacter(String str)
{
if(str == null || str.length() == 0) //빈 문자열일 경우 null 반환
return null;
else
{
char[] charArr = str.toCharArray(); //문자열을 배열로 변환
return charArr[0];
}
}
public static void main(String[] args)
{
String str = "Hello welcome to develop world!!";
System.out.println("문자열 : " + str);
System.out.print("문자열에 첫번째 문자는 : " + getFirstCharacter(str));
}
}
문자열 : Hello welcome to develop world!!
문자열에 첫번째 문자는 : H