>  기사  >  Java  >  Java의 substring() 함수

Java의 substring() 함수

王林
王林원래의
2024-08-30 15:35:52818검색

Java는 가장 널리 알려지고 사용되는 프로그래밍 언어 중 하나이며 다양한 기능과 방법을 제공합니다. 모든 프로그래밍 언어의 주요 측면 중 하나는 사용 가능한 데이터 유형 목록입니다. Java는 데이터 유형을 기본 및 비기본 데이터 유형으로 분류합니다. 여기서 문자열은 객체를 참조하므로 비기본 데이터 유형입니다. 이 String 개체에는 문자열에 대해 다양한 작업을 수행하는 다양한 메서드가 있습니다. 그러한 방법 중 하나가 java의 substring() 함수입니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

substring(): 문자열의 일부는 하위 문자열입니다. 그리고 substring() 메서드는 지정된 문자열의 일부를 반환합니다. 하위 문자열 메소드는 이 문자열의 하위 문자열인 새 문자열을 반환합니다.

이제 문자열 및 부분 문자열 방법이 무엇인지 배웠으니 부분 문자열 방법의 표준 구문을 이해해 보겠습니다.

구문:

public String substring(int beginIndex)

이것은 전달된 문자열의 하위 문자열인 새로운 새 문자열을 반환합니다. 필요한 매개변수는 부분 문자열()을 선택할 인덱스 지점을 지정하는 BeginIndex입니다. 지정한 인덱스의 문자부터 문자열 끝까지.

예외: 음수 인덱스가 전달되거나 문자열의 원래 길이보다 큰 인덱스가 전달되는 경우 "IndexOutOfBoundsException"이 발생합니다.

Java에서 substring() 함수는 어떻게 작동하나요?

Java의 substring() 함수가 호출되면 전달된 BeginIndex 매개변수를 기반으로 원래 문자열의 일부인 새 문자열을 생성하고 이를 반환합니다. BeginIndex가 전달되면 문자열 내에서 지정된 인덱스 값을 검색한 다음 지정된 인덱스에 있는 문자를 선택합니다. 한 버전에서는 BeginIndex가 전달되고, 하위 문자열 메서드의 다른 버전에서는 BeginIndex 및 endIndex가 제공됩니다. 문자열 데이터 유형은 변경할 수 없기 때문에 하위 문자열 메서드가 호출될 때마다 새 문자열이 생성된다는 사실을 이해하는 것이 중요합니다.

substring() 함수 구현 예시

아래 자바에서 substring() 함수를 구현하는 예를 살펴보겠습니다.

예시 #1

코드:

public class java_subs {
public static void main(String args[]) {
String sampleStr = new String("This is Java substring()");
System.out.print("The original substring: " +sampleStr);
System.out.print("\n Our new substring is : ");
System.out.println(sampleStr.substring(8));
}
}

코드 설명: 첫 번째 샘플 프로그램에는 시작 인덱스 매개변수가 있는 간단한 시연 하위 문자열 방법이 있습니다. 클래스를 만든 다음 메인 클래스를 추가했습니다. 변수 이름 및 값과 함께 문자열 데이터 유형을 선언했습니다. 처음에는 원본 문자열을 그대로 인쇄하겠습니다. 그런 다음 하위 문자열 방법의 효과를 사용하여 새 문자열을 인쇄합니다. "beginIndex"를 8번째 위치로 지정했습니다. 즉, 새 하위 문자열은 8번째 인덱스에서 시작하여 8번째 문자열의 끝까지 위치입니다. 위 코드를 실행하면 하위 문자열은 "Java substring()"이 될 것으로 예상됩니다. 출력은 아래 첨부된 스크린샷을 참고하세요.

출력:

Java의 substring() 함수

보시다시피 처음에는 원래 문자열을 그대로 인쇄한 다음 하위 문자열을 인쇄했습니다.

예시 #2

이제 첫 번째 예와 유사하지만 "endIndex" 매개변수가 추가된 또 다른 예를 살펴보겠습니다.

코드:

public class java_subs {
public static void main(String args[]) {
String sampleStr = new String("This is Java substring() and something extra.");
System.out.print("The original substring: " +sampleStr);
System.out.print("\n Our new substring: ");
System.out.println(sampleStr.substring(8, 24));
}
}

코드 설명: 이전 코드와 유사하게 내부에 클래스와 메인 클래스가 있습니다. 그런 다음 변수 이름과 값을 사용하여 문자열을 선언했는데, 이는 이전에 비해 상당히 깁니다. 다음으로 원래 문자열을 인쇄한 다음 새 문자열을 인쇄했습니다. 하위 문자열 메소드를 사용하여 두 개의 매개변수인 BeginIndex와 endIndex, 8과 24를 전달했습니다. 이 인덱스는 하위 문자열이 시작되어야 하는 지점과 끝나는 위치를 정의합니다. 이 예에서는 8번째 인덱스부터 하위 문자열이 시작되어 8번째 인덱스에서 최대 24번째 인덱스에 있는 문자를 선택합니다. 따라서 새 하위 문자열은 8번째와 24번째 인덱스 사이, 8번째 이전 및 24번째 인덱스 이후에 있게 됩니다. . 위 코드를 실행하면 하위 문자열은 “Java substring()”이 될 것으로 예상됩니다.

출력:

Java의 substring() 함수

출력에서 볼 수 있듯이 8

번째 이전 문자와 24번째번째 문자 이후 위치는 새로 생성된 하위 문자열의 일부가 아닙니다. 가장 널리 사용되는 하위 문자열 방법 중 하나는 시작과 끝 부분에서 불필요한 문자를 제거하는 것입니다.

예시 #3

코드:

public class java_subs {
public static void main(String args[]) {
String sampleStr = new String("This is just another example of java substring.");
System.out.print("The original substring: " +sampleStr);
int slength = sampleStr.length();
System.out.print("\n Our new substring: ");
System.out.println(sampleStr.substring(2, slength-9));
}
}

Code Explanation: In our third example, we have our class and main class within. We have a slightly different string here, and we have used the length method. Similar to earlier examples, we have printed our original string and then declared a new integer with slength, and the value is the length of the string. Then in our final print statement, our beginIndex is 2, meaning the substring will begin from the 2nd index, and the endIndex is slength -9, meaning whatever the length of the string is, the substring will end on 9 minus the original length. In our example, slength -9 will result in a substring to end on “s”.

Output:

Java의 substring() 함수

One of the important aspects to remember is, the original string is very long and holds the 1Gb size of an array. So, even if the substring being very small, it will be of 1GB. Though this will obviously stop the original string from being garbage collected, it is a case of memory leak, meaning a large amount of memory is acquired even though it won’t be used.

Conclusion

The string is one of the important data types, and the substring method simply returns a part of the original string. When the substring method is called, it creates a new string with an offset and count. We have demonstrated multiple examples with various methods to learn about substring. Code with its respective screenshots are attached.

위 내용은 Java의 substring() 함수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.