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

Java의 Split() 함수

PHPz
PHPz원래의
2024-08-30 15:35:26483검색

Java Split() 함수는 정규식이나 주어진 구분 기호를 기반으로 문자열을 문자열 배열로 분할하는 데 사용됩니다. 결과 객체는 분할된 문자열을 포함하는 배열입니다. 결과로 반환된 배열에서 요소 수에 대한 제한을 전달할 수 있습니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

예시를 보시죠

  • 문자열: Java@SplitFunctions
  • 정규식: @
  • 결과: “Java,” “SplitFunctions”

위의 예에서는 필수 정규식 일치 항목을 기준으로 문자열을 분할합니다.

구문:

split 함수의 구문은 다음과 같습니다.

public String[] split(String regex)

여기 위 서명에서 정규 표현식은 정규 표현식을 구분합니다. 문자열을 분할하는 데 사용되는 문자를 지정합니다. 마지막으로 결과 반환 값은 정규식 일치 항목을 기준으로 문자열을 분할하는 문자열 배열을 반환합니다.

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

Java Split() 함수에서는 다양한 방법을 사용하여 문자열을 분할합니다. 문자열 클래스는 문자열을 분할하는 두 가지 방법을 만듭니다.

다음과 같이 사용 가능한 시그니처를 살펴보겠습니다.

  • 공개 문자열[] 분할(문자열 정규식, 정수 제한)
  • 공개 문자열[] 분할(문자열 정규식)

1. 공개 문자열[] 분할(문자열 정규식)

이 방법은 주어진 문자열에 대한 정규식을 사용하여 문자열을 분할합니다. 전체 문자열이 문자열을 분할하고 결과 반환 형식이 배열 문자열입니다. Java 1.4에서는 위의 방법이 도입되었습니다. 문자열을 분할하고 해당 결과 출력을 보여주는 예를 살펴보겠습니다.

코드:

String string_1="JavaProgram";
System.out.println(Arrays.toString(s.split("a")));

출력:

Java의 Split() 함수

2. 공개 문자열[] 분할(문자열 정규식, 정수 제한)

Java 문자열을 제한된 수의 문자열로 분할해야 할 때 이 방법을 사용합니다. 이를 위해 우리는 이 방법을 사용합니다. 구분 기호를 쉼표로 사용하여 이름과 주소를 포함하는 문자열 변수가 있는 문자열의 예를 살펴보겠습니다. 다음 주소에는 쉼표가 있으므로 이 접근 방식을 사용합니다.

코드:

String s = "Spencer Plaza, New York, USA";
String[] data = s.split(",", 2);
System.out.println("Name = "+data[0]); // Spencer Plaza
System.out.println("Address = "+data[1]); //New York,USA

제한 매개변수는 선택사항입니다. 분할 횟수를 나타내는 정수와 분할 제한 이후의 항목은 배열에 포함되지 않습니다. 위의 첫 번째 방법은 한계를 0으로 전달하여 두 번째 방법을 사용합니다.

코드:

public String[] split(String regex) {
return split(regex, 0);
}

split() 함수의 예

다음의 예는 다음과 같습니다.

예시 #1

코드:

import java.io.*;
public class Program_1
{
public static void main(String args[]) {
String string_1 = new String("Welcome-to-JavaProgramming");
System.out.println("Output Value :" );
for (String res: string_1.split("-"))
{
System.out.println(res);
}
}
}

출력:

Java의 Split() 함수

구분자 인수를 제공하고 나누어야 하는 문자열에 대해 Split() 함수를 사용하여 구분자를 쉼표(,)로 사용하고 반환 결과는 배열 분할이 될 것입니다. 출력은 아래와 같이 각 분할 작업 후에 배열 요소라고 하는 각 문자열을 인쇄합니다.

예시 #2

코드:

import java.io.*;
class Program_2
{
public static void main(String []args)
{
String string_1 = "String, Functions, Split, Methods, Demo";
String[] split_array = string_1.split(", ");
for (int i=0; i < split_array.length; i++)
{
System.out.println(split_array [i]);
}
}
}

출력:

Java의 Split() 함수

여기서 이 함수의 두 번째 인수로 제한하는 분할을 전달합니다. 이는 분할 문자열의 수를 제한합니다.

예시 #3

코드:

import java.io.*;
public class Program_3
{
public static void main(String[] args)
{
String string_1 = "JavatSplittFunction";
System.out.println("Result:");
String[] arrSplit = string_1.split("t", 0);
for (String a : arrSplit)
{
System.out.println(a);
}
System.out.println("Length of Split Array: "+ arrSplit.length);
}
}

출력:

Java의 Split() 함수

제한 매개변수가 있는 Split() 메서드

limit 매개변수가 있는 Split() 메서드는 제한된 수의 문자열을 분할합니다. Limit 매개변수가 있는 Split()과 Split()의 차이점은 분할 후 반환되는 문자열 수를 제한한다는 것입니다. 제한을 위해서는 Split() 함수에 입력 매개변수를 제공해야 합니다. Limit 매개변수와 함께 Split() 메소드의 사용법을 살펴보겠습니다.

public String[] split(String regex, int limit)

여기서 regex 매개변수는 정규식을 구분하며, 한계는 결과 임계값에 대한 것입니다. 한도는 3가지 값으로 구성됩니다.

  • limit > 0: If the limit is set as >0, the resultant array length must not be more significant than n, which is applied at most limit-1 times. The last entry contains input with the last matched delimiter.
  • limit < 0:If the limit is set as <0, the resultant array with any number of lengths can apply the pattern as many times as possible.
  • limit = 0: If the limit is set as equal to 0, the resulting array has any number of lengths, but the empty string will be discarded, and this limit is functional as many times as possible.
  • This parameter’s return value will be an array of string objects by splitting the given string accords to the limit parameter. The PatternSyntacException will occur if the given regular expression syntax is invalid while executing the code. Let’s see the example program for the split() method on a string with the limit parameter.

    Example #4

    Code:

    public class Program_4
    {
    public static void main(String args[])
    {
    String string_1 = "238-347-9288";
    String[] stringArray = string_1.split("8",2);
    System.out.println("Split() Method with the Limit Parameter");
    System.out.println("\nLimit Value is +ve");
    System.out.println("Sub-Strings: "+stringArray.length);
    for(int i=0; i<stringArray.length; i++)
    {  System.out.println("string_1["+i+"] : "+stringArray[i]);
    }
    String[] stringArray2 = string_1.split("8",-3);
    System.out.println("Limit Value is -ve");
    System.out.println("Sub-Strings: "+stringArray2.length);
    for(int i=0; i<stringArray2.length; i++)
    {
    System.out.println("string_1["+i+"] : "+stringArray2[i]);
    }
    String[] stringArray3 = string_1.split("8",0);
    System.out.println("Limit Value is 0");
    System.out.println("Sub-Strings: "+stringArray3.length);
    for(int i=0; i<stringArray3.length; i++)
    {
    System.out.println("string_1["+i+"] : "+stringArray3[i]);
    }
    }
    }

    Output:

    Java의 Split() 함수

    The above program shows that the split() method works by the specified limit parameter, as seen by the output:

    1. The number of substrings in the resulting array is two when the limit is 2.
    2. Setting the limit to -3 causes the string to split into 4 substrings, including the trailing spaces.
    3. If you set the limit to 0, it eliminates the trailing spaces. As a result, the input string splits into 2 substrings.

    Conclusion

    At the end of the ‘Split() Function in Java’ article, we learned how to split strings using the split() method in different Java approaches. I hope in this article; you understand everything that has been shared with examples.

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

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