program story

하위 문자열 색인 범위

inputbox 2020. 11. 7. 09:29
반응형

하위 문자열 색인 범위


암호:

public class Test {
    public static void main(String[] args) {
        String str = "University";
        System.out.println(str.substring(4, 7));
    }   
}

산출: ers

부분 문자열 방법이 어떻게 작동하는지 정말 이해하지 못합니다. 인덱스가 0에서 시작합니까? 0으로 시작하면 e인덱스 4에 있지만 char i은 7에 있으므로 출력은 ersi.


0 : U

1 : n

2 : 나는

3 : v

4 : e

5 : r

6 : 초

7 : 나는

8 : t

9 : y

시작 색인이 포함됩니다.

끝 색인은 배타적입니다.

Javadoc 링크


둘 다 0부터 시작하지만 시작은 포함되고 끝은 제외됩니다. 이렇게하면 결과 문자열이 길이가 start - end됩니다.

substring작업을 더 쉽게하기 위해 문자가 인덱스 사이에 있다고 상상해보십시오 .

0 1 2 3 4 5 6 7 8 9 10  <- available indexes for substring 
 u n i v E R S i t y
        ↑     ↑
      start  end --> range of "E R S"

문서 인용 :

하위 문자열은 지정된 위치에서 시작 beginIndex하여 index의 문자까지 확장됩니다 endIndex - 1. 따라서 부분 문자열의 길이는 endIndex-beginIndex입니다.


javadoc을 참조하십시오 . 첫 번째 인수에 대해서는 포함 색인이고 두 번째 인수에 대해서는 배타적입니다.


당신처럼 나는 그것이 자연스럽게 오는 것을 찾지 못했습니다. 나는 일반적으로

  • 반환 된 문자열 길이

    lastIndex-firstIndex

  • 문자가 없어도 문자열의 길이를 lastIndex로 사용할 수 있으며 참조하려고하면 예외가 발생합니다.

그래서

"University".substring(6, 10)

sity"위치 10에 문자가 없더라도 4 문자 문자열 "을 리턴합니다 .


public String substring(int beginIndex, int endIndex)

beginIndex-시작 색인 (포함).

endIndex-배타적 끝 색인.

예:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3, 8));
    }
 }

출력 : "lo Wo"

3-7 인덱스.

또한 다른 종류의 substring()방법이 있습니다.

public String substring(int beginIndex)

beginIndex-시작 색인 (포함). beginIndex기본 문자열의 끝 부터 시작하여 하위 문자열을 반환합니다 .

예:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3));
    }
}

Output: "lo World"

From 3 to the last index.


Yes, the index starts at zero (0). The two arguments are startIndex and endIndex, where per the documentation:

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

See here for more information.


The substring starts at, and includes the character at the location of the first number given and goes to, but does not include the character at the last number given.


For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing. I would understand substring(startIndex, length) to remember that.


public class SubstringExample
{
    public static void main(String[] args) 
    {
        String str="OOPs is a programming paradigm...";

        System.out.println(" Length is: " + str.length());

        System.out.println(" Substring is: " + str.substring(10, 30));
    }
}

Output:

length is: 31

Substring is: programming paradigm

참고URL : https://stackoverflow.com/questions/4570037/substring-index-range

반응형