자바 문자열 추출 - jaba munjayeol chuchul

- 문자열 대상으로 특정 위치의 문자를 추출하기 -


charAt()

char charAt(int index)

charAt() 함수는 입력받은 인자값(index) 의 위치에 있는 문자를 뽑아내는 함수


예제 1) charAt() 기본 사용법

public class CharAtTest{
    public static void main(String[] args){
        String str = "charAtT";
        System.out.println( str.charAt(4) );  // A
    }
}

왜 저런 결과가 나오는지 알아보자

str.charAt(4는 해당 문자열의 4번 index 의 문자를 추출하겠다 라는 의미이다.

문자열 c h a r A t T
index 0 1 2 3 4 5 6

0부터 시작해서 4번째의 index를 가지는 문자는 "A" 이므로 "A" 가 출력되는것이다.

이 게시물은 첫 번째를 얻는 방법에 대해 설명합니다. n Java에서 문자열의 문자, 여기서 n 음이 아닌 정수입니다.

1. 사용 substring() 방법

첫 번째를 얻으려면 n 문자열의 문자, 우리는 시작 인덱스를 0으로, 끝 인덱스를 다음과 같이 전달할 수 있습니다. n ~로 substring() 방법. 참고로 substring() 메서드 반환 IndexOutOfBoundsException 끝 인덱스가 문자열의 길이보다 큰 경우. 이것은 아래와 같이 삼항 연산자를 사용하여 처리할 수 있습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

classMain

{

    publicstaticString firstNChars(Stringstr,intn) {

        if(str== null){

            returnnull;

        }

        returnstr.length()< n?str: str.substring(0,n);

    }

    publicstaticvoid main(String[]args)

    {

        Stringstr="Techie Delight";

        int n=6;

        Stringtruncated =firstNChars(str,n);

        System.out.println(truncated);        // Techie

    }

}

다운로드  코드 실행

 
삼항 연산자 대신 문자열의 최소 길이와 n 끝 인덱스로 substring() 방법.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

classMain

{

    publicstaticString firstNChars(Stringstr,intn) {

        if(str== null){

            returnnull;

        }

        returnstr.substring(0, Math.min(str.length(), n));

    }

    publicstatic voidmain(String[]args)

    {

        Stringstr="Techie Delight";

        intn=6;

        String truncated=firstNChars(str,n);

        System.out.println(truncated);        // Techie

    }

}

다운로드  코드 실행

2. Apache Commons Lang 사용하기

Apache Commons Lang 라이브러리 StringUtils 클래스는 null-safe 부분 문자열 추출을 위한 여러 유틸리티 메서드를 제공합니다. 첫 번째를 얻으려면 n 문자열의 문자, 우리는 오버로드 버전을 사용할 수 있습니다 substring() 지정된 시작 위치에서 지정된 끝 위치까지 부분 문자열을 반환하는 메서드입니다. 다음과 같은 경우 예외를 명시적으로 처리할 필요가 없습니다. n 문자열의 길이보다 큽니다.

importorg.apache.commons.lang3.StringUtils;

classMain

{

    publicstaticvoidmain(String[]args)

    {

        Stringstr="Techie Delight";

        int n=6;

        Stringtruncated =StringUtils.substring(str,0, n);

        System.out.println(truncated);        // Techie

    }

}

코드 다운로드

 
그만큼 StringUtils 클래스도 가지고 있습니다 left() 특히 가장 왼쪽을 추출하는 방법 n 문자열의 문자. 문자열이 null이거나 n 문자를 사용할 수 없는 경우 예외 없이 원래 문자열을 반환합니다.

importorg.apache.commons.lang3.StringUtils;

classMain

{

    publicstaticvoidmain(String[]args)

    {

        Stringstr="Techie Delight";

        int n=6;

        Stringtruncated =StringUtils.left(str,n);

        System.out.println(truncated);        // Techie

    }

}

코드 다운로드

3. Guava바 사용하기

또는 Guava바를 사용할 수 있습니다. Ascii.truncate() 주어진 문자열을 특정 길이로 자르는 메소드.

importcom.google.common.base.Ascii;

classMain

{

    publicstaticvoidmain(String[]args)

    {

        Stringstr="Techie Delight";

        int n=6;

        Stringtruncated =Ascii.truncate(str,n, "");

        System.out.println(truncated);            // Techie

    }

}

코드 다운로드

4. 사용 String.format() 방법

마지막으로 다음을 사용하여 문자열의 형식을 간단히 지정할 수 있습니다. String.format() 출력에 쓸 최소 문자 수를 나타내는 너비를 사용하는 메서드입니다.

classMain

{

    publicstaticvoid main(String[]args)

    {

        Stringstr="Techie Delight";

        int n=6;

        Stringtruncated =String.format("%."+n +"s",str);

        System.out.println(truncated);        // Techie

    }

}

다운로드  코드 실행

그게 다 우선이야 n Java에서 문자열의 문자.

읽어 주셔서 감사합니다.

우리의 온라인 컴파일러 C, C++, Java, Python, JavaScript, C#, PHP 및 기타 널리 사용되는 프로그래밍 언어를 사용하여 주석에 코드를 게시합니다.

우리처럼? 우리를 친구에게 소개하고 우리가 성장할 수 있도록 도와주세요. 행복한 코딩 :)