logo

Cum să împărțiți un șir în Java cu Delimiter?

În Java, sfoară de despicare este o operație importantă și utilizată de obicei la codificare. Java oferă mai multe moduri de a împărțiți șirul . Dar cea mai obișnuită modalitate este de a folosi metoda split(). din clasa String. În această secțiune, vom învăța cum să împărțiți un șir în Java cu delimitator. Împreună cu aceasta, vom învăța și alte metode de a împărți șirul, cum ar fi utilizarea clasei StringTokenizer, Metoda Scanner.useDelimiter(). . Înainte de a trece la subiect, să înțelegem ce este delimitator.

Ce este un delimitator?

În Java , delimitatori sunt caracterele care despart (separă) șirul în jetoane. Java ne permite să definim orice caracter ca delimitator. Există multe metode de împărțire a șirurilor oferite de Java care utilizează caracterul de spațiu alb ca delimitator. The delimitator de spații albe este delimitator implicit în Java.

Înainte de a trece la program, să înțelegem conceptul de șir.

Șirul este alcătuit din două tipuri de text care sunt jetoane și delimitatori. Jetoanele sunt cuvintele care au sens, iar delimitatorii sunt caracterele care despart sau separă tokenurile. Să înțelegem printr-un exemplu.

Pentru a înțelege delimitator în Java , trebuie să fim prietenoși cu Expresie regulată Java . Este necesar atunci când delimitatorul este folosit ca caracter special în expresiile regulate, cum ar fi (.) și (|).

Exemplu de delimitator

Şir: Javatpoint este cel mai bun site web pentru a învăța noi tehnologii.

În șirul de mai sus, jetoanele sunt, Javatpoint, este cel mai bun site web pentru a învăța noi tehnologii , iar delimitatorii sunt spații albe între cele două jetoane.

Cum să împărțiți un șir în Java cu Delimiter?

Java oferă următoarea modalitate de a împărți un șir în token-uri:

Folosind metoda Scanner.next().

Este metoda clasei Scanner. Găsește și returnează următorul token de la scaner. Împarte șirul în token-uri prin delimitarea spațiului alb. Tokenul complet este identificat de intrarea care se potrivește cu modelul delimitatorului.

Sintaxă:

 public String next(); 

Aruncă NoSuchElementException dacă următorul jeton nu este disponibil. De asemenea, aruncă IllegalStateException dacă scanerul de intrare este închis.

Să creăm un program care împarte un obiect șir folosind metoda next() care utilizează spații albe pentru a împărți șirul în jetoane.

SplitStringExample1.java

 import java.util.Scanner; public class SplitStringExample1 { public static void main(String[] args) { //declaring a string String str='Javatpoint is the best website to learn new technologies'; //constructor of the Scanner class Scanner sc=new Scanner(str); while (sc.hasNext()) { //invoking next() method that splits the string String tokens=sc.next(); //prints the separated tokens System.out.println(tokens); //closing the scanner sc.close(); } } } 

Ieșire:

buclă dactilografiată pentru fiecare
 Javatpoint is the best website to learn new technologies 

În programul de mai sus, un punct de observat că în constructorul clasei Scanner în loc să trecem System.in am trecut o variabilă șir str. Am făcut acest lucru deoarece înainte de a manipula șirul, trebuie să citim șirul.

Folosind metoda String.split().

The Despică() metoda de Şir clasă este folosit pentru a împărți un șir într-o matrice de obiecte String pe baza delimitatorului specificat care se potrivește cu expresia regulată. De exemplu, luați în considerare următorul șir:

 String str= 'Welcome,to,the,word,of,technology'; 

Șirul de mai sus este separat prin virgule. Putem împărți șirul de mai sus folosind următoarea expresie:

 String[] tokens=s.split(','); 

Expresia de mai sus împarte șirul în jetoane atunci când jetoanele sunt separate prin virgulă (,) caracterului delimitator specificat. Șirul specificat împărțit în următoarele obiecte șir:

 Welcome to the word of technology 

Există două variante ale metodelor split():

  • split(String regex)
  • split(String regex, int limit)

String.split(String regex)

Împarte șirul conform expresiei regulate specificate. Putem folosi un punct (.), spațiu ( ), virgulă (,) și orice caracter (cum ar fi z, a, g, l etc.)

Sintaxă:

 public String[] split(String regex) 

Metoda parsează o expresie regulată delimitare ca argument. Returnează o matrice de obiecte String. Aruncă PatternSyntaxException dacă expresia regulată analizată are o sintaxă nevalidă.

Să folosim metoda split() și să împărțim șirul prin virgulă.

SplitStringExample2.java

 public class SplitStringExample2 { public static void main(String args[]) { //defining a String object String s = &apos;Life,is,your,creation&apos;; //split string delimited by comma String[] stringarray = s.split(&apos;,&apos;); //we can use dot, whitespace, any character //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Life is your creation </pre> <p>In the above example, the string object is delimited by a comma. The split() method splits the string when it finds the comma as a delimiter.</p> <p>Let&apos;s see another example in which we will use multiple delimiters to split the string.</p> <p> <strong>SplitStringExample3.java</strong> </p> <pre> public class SplitStringExample3 { public static void main(String args[]) { //defining a String object String s = &apos;If you don&apos;t like something, change.it.&apos;; //split string by multiple delimiters String[] stringarray = s.split(&apos;[, . &apos;]+&apos;); //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> If you don t like something change it </pre> <p> <strong>String.split(String regex, int limit)</strong> </p> <p>It allows us to split string specified by delimiter but into a limited number of tokens. The method accepts two parameters regex (a delimiting regular expression) and limit. The limit parameter is used to control the number of times the pattern is applied that affects the resultant array. It returns an array of String objects computed by splitting the given string according to the limit parameter.</p> <p>There is a slight difference between the variant of the split() methods that it limits the number of tokens returned after invoking the method.</p> <p> <strong>Syntax:</strong> </p> <pre> public String[] split(String regex, int limit) </pre> <p>It throws <strong>PatternSyntaxException</strong> if the parsed regular expression has an invalid syntax.</p> <p>The limit parameter may be positive, negative, or equal to the limit.</p> <p> <strong>SplitStringExample4.java</strong> </p> <pre> public class SplitStringExample4 { public static void main(String args[]) { String str1 = &apos;468-567-7388&apos;; String str2 = &apos;Life,is,your,creation&apos;; String str3 = &apos;Hello! how are you?&apos;; String[] stringarray1 = str1.split(&apos;8&apos;,2); System.out.println(&apos;When the limit is positive:&apos;); System.out.println(&apos;Number of tokens: &apos;+stringarray1.length); for(int i=0; i<stringarray1.length; i++) { system.out.println(stringarray1[i]); } string[] stringarray2="str2.split(&apos;y&apos;,-3);" system.out.println('
when the limit is negative: '); system.out.println('number of tokens: '+stringarray2.length); for(int i="0;" i<stringarray2.length; system.out.println(stringarray2[i]); stringarray3="str3.split(&apos;!&apos;,0);" equal to 0:'); '+stringarray3.length); i<stringarray3.length; system.out.println(stringarray3[i]); < pre> <p> <strong>Output:</strong> </p> <pre> When the limit is positive: Number of tokens: 2 46 -567-7388 When the limit is negative: Number of tokens: 2 Life,is, our,creation When the limit is equal to 0: Number of tokens: 2 Hello how are you? </pre> <p>In the above code snippet, we see that:</p> <ul> <li>When the limit is 2, the number of tokens in the string array is two.</li> <li>When the limit is -3, the specified string is split into 2 tokens. It includes the trailing spaces.</li> <li>When the limit is 0, the specified string is split into 2 tokens. In this case, trailing space is omitted.</li> </ul> <h3>Example of Pipe Delimited String</h3> <p>Splitting a string delimited by pipe (|) is a little bit tricky. Because the pipe is a special character in Java regular expression.</p> <p>Let&apos;s create a string delimited by pipe and split it by pipe.</p> <p> <strong>SplitStringExample5.java</strong> </p> <pre> public class SplitStringExample5 { public static void main(String args[]) { //defining a String object String s = &apos;Life|is|your|creation&apos;; //split string delimited by comma String[] stringarray = s.split(&apos;|&apos;); //we can use dot, whitespace, any character //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> L i f e | i s | y o u r | c r e a t i o n </pre> <p>In the above example, we see that it does not produce the same output as other delimiter yields. It should produce an array of tokens, <strong>life, yours,</strong> and <strong>creation</strong> , but it is not. It gives the result, as we have seen in the output above.</p> <p>The reason behind it that the regular expression engine interprets the pipe delimiter as a <strong>Logical OR operator</strong> . The regex engine splits the String on empty String.</p> <p>In order to resolve this problem, we must <strong>escape</strong> the pipe character when passed to the split() method. We use the following statement to escape the pipe character:</p> <pre> String[] stringarray = s.split(&apos;\|&apos;); </pre> <p>Add a pair of <strong>backslash (\)</strong> before the delimiter to escape the pipe. After doing the changes in the above program, the regex engine interprets the pipe character as a delimiter.</p> <p>Another way to escape the pipe character is to put the pipe character inside a pair of square brackets, as shown below. In the Java regex API, the pair of square brackets act as a character class.</p> <pre> String[] stringarray = s.split(&apos;[|]&apos;); </pre> <p>Both the above statements yield the following output:</p> <p> <strong>Output:</strong> </p> <pre> Life is your creation </pre> <h3>Using StringTokenizer Class</h3> <p>Java <strong>StringTokenizer</strong> is a legacy class that is defined in java.util package. It allows us to split the string into tokens. It is not used by the programmer because the split() method of the String class does the same work. So, the programmer prefers the split() method instead of the StringTokenizer class. We use the following two methods of the class:</p> <p> <strong>StringTokenizer.hasMoreTokens()</strong> </p> <p>The method iterates over the string and checks if there are more tokens available in the tokenizer string. It returns true if there is one token is available in the string after the current position, else returns false. It internally calls the <strong>nextToken()</strong> method if it returns true and the nextToken() method returns the token.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean hasMoreTokens() </pre> <p> <strong>StringTokenizer.nextToken()</strong> </p> <p>It returns the next token from the string tokenizer. It throws <strong>NoSuchElementException</strong> if the tokens are not available in the string tokenizer.</p> <p> <strong>Syntax:</strong> </p> <pre> public String nextToken() </pre> <p>Let&apos;s create a program that splits the string using the StringTokenizer class.</p> <p> <strong>SplitStringExample6.java</strong> </p> <pre> import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = &apos;Welcome/to/Javatpoint&apos;; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, &apos;/&apos;); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Welcome to Javatpoint </pre> <h2>Using Scanner.useDelimiter() Method</h2> <p>Java <strong>Scanner</strong> class provides the <strong>useDelimiter()</strong> method to split the string into tokens. There are two variants of the useDelimiter() method:</p> <ul> <li>useDelimiter(Pattern pattern)</li> <li>useDelimiter(String pattern)</li> </ul> <h3>useDelimiter(Pattern pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(Pattern pattern) </pre> <h3>useDelimiter(String pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to a pattern that constructs from the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(String pattern) </pre> <h4>Note: Both the above methods behave in the same way, as invoke the useDelimiter(Pattern.compile(pattern)).</h4> <p>In the following program, we have used the useDelimiter() method to split the string.</p> <p> <strong>SplitStringExample7.java</strong> </p> <pre> import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner(&apos;Do/your/work/self&apos;); //Initialize the string delimiter scan.useDelimiter(&apos;/&apos;); //checks if the tokenized Strings has next token while(scan.hasNext()) { //prints the next token System.out.println(scan.next()); } //closing the scanner scan.close(); } } </pre> <p> <strong>Output:</strong> </p> <pre> Do your work self </pre> <hr></stringarray.length;></pre></stringarray1.length;></pre></stringarray.length;></pre></stringarray.length;>

În exemplul de mai sus, obiectul șir este delimitat de o virgulă. Metoda split() împarte șirul atunci când găsește virgula ca delimitator.

Să vedem un alt exemplu în care vom folosi mai mulți delimitatori pentru a împărți șirul.

SplitStringExample3.java

 public class SplitStringExample3 { public static void main(String args[]) { //defining a String object String s = &apos;If you don&apos;t like something, change.it.&apos;; //split string by multiple delimiters String[] stringarray = s.split(&apos;[, . &apos;]+&apos;); //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> If you don t like something change it </pre> <p> <strong>String.split(String regex, int limit)</strong> </p> <p>It allows us to split string specified by delimiter but into a limited number of tokens. The method accepts two parameters regex (a delimiting regular expression) and limit. The limit parameter is used to control the number of times the pattern is applied that affects the resultant array. It returns an array of String objects computed by splitting the given string according to the limit parameter.</p> <p>There is a slight difference between the variant of the split() methods that it limits the number of tokens returned after invoking the method.</p> <p> <strong>Syntax:</strong> </p> <pre> public String[] split(String regex, int limit) </pre> <p>It throws <strong>PatternSyntaxException</strong> if the parsed regular expression has an invalid syntax.</p> <p>The limit parameter may be positive, negative, or equal to the limit.</p> <p> <strong>SplitStringExample4.java</strong> </p> <pre> public class SplitStringExample4 { public static void main(String args[]) { String str1 = &apos;468-567-7388&apos;; String str2 = &apos;Life,is,your,creation&apos;; String str3 = &apos;Hello! how are you?&apos;; String[] stringarray1 = str1.split(&apos;8&apos;,2); System.out.println(&apos;When the limit is positive:&apos;); System.out.println(&apos;Number of tokens: &apos;+stringarray1.length); for(int i=0; i<stringarray1.length; i++) { system.out.println(stringarray1[i]); } string[] stringarray2="str2.split(&apos;y&apos;,-3);" system.out.println(\'
when the limit is negative: \'); system.out.println(\'number of tokens: \'+stringarray2.length); for(int i="0;" i<stringarray2.length; system.out.println(stringarray2[i]); stringarray3="str3.split(&apos;!&apos;,0);" equal to 0:\'); \'+stringarray3.length); i<stringarray3.length; system.out.println(stringarray3[i]); < pre> <p> <strong>Output:</strong> </p> <pre> When the limit is positive: Number of tokens: 2 46 -567-7388 When the limit is negative: Number of tokens: 2 Life,is, our,creation When the limit is equal to 0: Number of tokens: 2 Hello how are you? </pre> <p>In the above code snippet, we see that:</p> <ul> <li>When the limit is 2, the number of tokens in the string array is two.</li> <li>When the limit is -3, the specified string is split into 2 tokens. It includes the trailing spaces.</li> <li>When the limit is 0, the specified string is split into 2 tokens. In this case, trailing space is omitted.</li> </ul> <h3>Example of Pipe Delimited String</h3> <p>Splitting a string delimited by pipe (|) is a little bit tricky. Because the pipe is a special character in Java regular expression.</p> <p>Let&apos;s create a string delimited by pipe and split it by pipe.</p> <p> <strong>SplitStringExample5.java</strong> </p> <pre> public class SplitStringExample5 { public static void main(String args[]) { //defining a String object String s = &apos;Life|is|your|creation&apos;; //split string delimited by comma String[] stringarray = s.split(&apos;|&apos;); //we can use dot, whitespace, any character //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> L i f e | i s | y o u r | c r e a t i o n </pre> <p>In the above example, we see that it does not produce the same output as other delimiter yields. It should produce an array of tokens, <strong>life, yours,</strong> and <strong>creation</strong> , but it is not. It gives the result, as we have seen in the output above.</p> <p>The reason behind it that the regular expression engine interprets the pipe delimiter as a <strong>Logical OR operator</strong> . The regex engine splits the String on empty String.</p> <p>In order to resolve this problem, we must <strong>escape</strong> the pipe character when passed to the split() method. We use the following statement to escape the pipe character:</p> <pre> String[] stringarray = s.split(&apos;\|&apos;); </pre> <p>Add a pair of <strong>backslash (\)</strong> before the delimiter to escape the pipe. After doing the changes in the above program, the regex engine interprets the pipe character as a delimiter.</p> <p>Another way to escape the pipe character is to put the pipe character inside a pair of square brackets, as shown below. In the Java regex API, the pair of square brackets act as a character class.</p> <pre> String[] stringarray = s.split(&apos;[|]&apos;); </pre> <p>Both the above statements yield the following output:</p> <p> <strong>Output:</strong> </p> <pre> Life is your creation </pre> <h3>Using StringTokenizer Class</h3> <p>Java <strong>StringTokenizer</strong> is a legacy class that is defined in java.util package. It allows us to split the string into tokens. It is not used by the programmer because the split() method of the String class does the same work. So, the programmer prefers the split() method instead of the StringTokenizer class. We use the following two methods of the class:</p> <p> <strong>StringTokenizer.hasMoreTokens()</strong> </p> <p>The method iterates over the string and checks if there are more tokens available in the tokenizer string. It returns true if there is one token is available in the string after the current position, else returns false. It internally calls the <strong>nextToken()</strong> method if it returns true and the nextToken() method returns the token.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean hasMoreTokens() </pre> <p> <strong>StringTokenizer.nextToken()</strong> </p> <p>It returns the next token from the string tokenizer. It throws <strong>NoSuchElementException</strong> if the tokens are not available in the string tokenizer.</p> <p> <strong>Syntax:</strong> </p> <pre> public String nextToken() </pre> <p>Let&apos;s create a program that splits the string using the StringTokenizer class.</p> <p> <strong>SplitStringExample6.java</strong> </p> <pre> import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = &apos;Welcome/to/Javatpoint&apos;; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, &apos;/&apos;); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Welcome to Javatpoint </pre> <h2>Using Scanner.useDelimiter() Method</h2> <p>Java <strong>Scanner</strong> class provides the <strong>useDelimiter()</strong> method to split the string into tokens. There are two variants of the useDelimiter() method:</p> <ul> <li>useDelimiter(Pattern pattern)</li> <li>useDelimiter(String pattern)</li> </ul> <h3>useDelimiter(Pattern pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(Pattern pattern) </pre> <h3>useDelimiter(String pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to a pattern that constructs from the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(String pattern) </pre> <h4>Note: Both the above methods behave in the same way, as invoke the useDelimiter(Pattern.compile(pattern)).</h4> <p>In the following program, we have used the useDelimiter() method to split the string.</p> <p> <strong>SplitStringExample7.java</strong> </p> <pre> import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner(&apos;Do/your/work/self&apos;); //Initialize the string delimiter scan.useDelimiter(&apos;/&apos;); //checks if the tokenized Strings has next token while(scan.hasNext()) { //prints the next token System.out.println(scan.next()); } //closing the scanner scan.close(); } } </pre> <p> <strong>Output:</strong> </p> <pre> Do your work self </pre> <hr></stringarray.length;></pre></stringarray1.length;></pre></stringarray.length;>

String.split(String regex, limita int)

f-string python

Ne permite să împărțim șirul specificat de delimitator, dar într-un număr limitat de jetoane. Metoda acceptă doi parametri regex (o expresie regulată delimitantă) și limit. Parametrul limită este utilizat pentru a controla de câte ori este aplicat modelul care afectează matricea rezultată. Returnează o matrice de obiecte String calculate prin împărțirea șirului dat în funcție de parametrul limită.

Există o mică diferență între varianta metodelor split() că limitează numărul de jetoane returnate după invocarea metodei.

Sintaxă:

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

Aruncă PatternSyntaxException dacă expresia regulată analizată are o sintaxă nevalidă.

Parametrul limită poate fi pozitiv, negativ sau egal cu limită.

SplitStringExample4.java

 public class SplitStringExample4 { public static void main(String args[]) { String str1 = &apos;468-567-7388&apos;; String str2 = &apos;Life,is,your,creation&apos;; String str3 = &apos;Hello! how are you?&apos;; String[] stringarray1 = str1.split(&apos;8&apos;,2); System.out.println(&apos;When the limit is positive:&apos;); System.out.println(&apos;Number of tokens: &apos;+stringarray1.length); for(int i=0; i<stringarray1.length; i++) { system.out.println(stringarray1[i]); } string[] stringarray2="str2.split(&apos;y&apos;,-3);" system.out.println(\'
when the limit is negative: \'); system.out.println(\'number of tokens: \'+stringarray2.length); for(int i="0;" i<stringarray2.length; system.out.println(stringarray2[i]); stringarray3="str3.split(&apos;!&apos;,0);" equal to 0:\'); \'+stringarray3.length); i<stringarray3.length; system.out.println(stringarray3[i]); < pre> <p> <strong>Output:</strong> </p> <pre> When the limit is positive: Number of tokens: 2 46 -567-7388 When the limit is negative: Number of tokens: 2 Life,is, our,creation When the limit is equal to 0: Number of tokens: 2 Hello how are you? </pre> <p>In the above code snippet, we see that:</p> <ul> <li>When the limit is 2, the number of tokens in the string array is two.</li> <li>When the limit is -3, the specified string is split into 2 tokens. It includes the trailing spaces.</li> <li>When the limit is 0, the specified string is split into 2 tokens. In this case, trailing space is omitted.</li> </ul> <h3>Example of Pipe Delimited String</h3> <p>Splitting a string delimited by pipe (|) is a little bit tricky. Because the pipe is a special character in Java regular expression.</p> <p>Let&apos;s create a string delimited by pipe and split it by pipe.</p> <p> <strong>SplitStringExample5.java</strong> </p> <pre> public class SplitStringExample5 { public static void main(String args[]) { //defining a String object String s = &apos;Life|is|your|creation&apos;; //split string delimited by comma String[] stringarray = s.split(&apos;|&apos;); //we can use dot, whitespace, any character //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> L i f e | i s | y o u r | c r e a t i o n </pre> <p>In the above example, we see that it does not produce the same output as other delimiter yields. It should produce an array of tokens, <strong>life, yours,</strong> and <strong>creation</strong> , but it is not. It gives the result, as we have seen in the output above.</p> <p>The reason behind it that the regular expression engine interprets the pipe delimiter as a <strong>Logical OR operator</strong> . The regex engine splits the String on empty String.</p> <p>In order to resolve this problem, we must <strong>escape</strong> the pipe character when passed to the split() method. We use the following statement to escape the pipe character:</p> <pre> String[] stringarray = s.split(&apos;\|&apos;); </pre> <p>Add a pair of <strong>backslash (\)</strong> before the delimiter to escape the pipe. After doing the changes in the above program, the regex engine interprets the pipe character as a delimiter.</p> <p>Another way to escape the pipe character is to put the pipe character inside a pair of square brackets, as shown below. In the Java regex API, the pair of square brackets act as a character class.</p> <pre> String[] stringarray = s.split(&apos;[|]&apos;); </pre> <p>Both the above statements yield the following output:</p> <p> <strong>Output:</strong> </p> <pre> Life is your creation </pre> <h3>Using StringTokenizer Class</h3> <p>Java <strong>StringTokenizer</strong> is a legacy class that is defined in java.util package. It allows us to split the string into tokens. It is not used by the programmer because the split() method of the String class does the same work. So, the programmer prefers the split() method instead of the StringTokenizer class. We use the following two methods of the class:</p> <p> <strong>StringTokenizer.hasMoreTokens()</strong> </p> <p>The method iterates over the string and checks if there are more tokens available in the tokenizer string. It returns true if there is one token is available in the string after the current position, else returns false. It internally calls the <strong>nextToken()</strong> method if it returns true and the nextToken() method returns the token.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean hasMoreTokens() </pre> <p> <strong>StringTokenizer.nextToken()</strong> </p> <p>It returns the next token from the string tokenizer. It throws <strong>NoSuchElementException</strong> if the tokens are not available in the string tokenizer.</p> <p> <strong>Syntax:</strong> </p> <pre> public String nextToken() </pre> <p>Let&apos;s create a program that splits the string using the StringTokenizer class.</p> <p> <strong>SplitStringExample6.java</strong> </p> <pre> import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = &apos;Welcome/to/Javatpoint&apos;; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, &apos;/&apos;); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Welcome to Javatpoint </pre> <h2>Using Scanner.useDelimiter() Method</h2> <p>Java <strong>Scanner</strong> class provides the <strong>useDelimiter()</strong> method to split the string into tokens. There are two variants of the useDelimiter() method:</p> <ul> <li>useDelimiter(Pattern pattern)</li> <li>useDelimiter(String pattern)</li> </ul> <h3>useDelimiter(Pattern pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(Pattern pattern) </pre> <h3>useDelimiter(String pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to a pattern that constructs from the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(String pattern) </pre> <h4>Note: Both the above methods behave in the same way, as invoke the useDelimiter(Pattern.compile(pattern)).</h4> <p>In the following program, we have used the useDelimiter() method to split the string.</p> <p> <strong>SplitStringExample7.java</strong> </p> <pre> import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner(&apos;Do/your/work/self&apos;); //Initialize the string delimiter scan.useDelimiter(&apos;/&apos;); //checks if the tokenized Strings has next token while(scan.hasNext()) { //prints the next token System.out.println(scan.next()); } //closing the scanner scan.close(); } } </pre> <p> <strong>Output:</strong> </p> <pre> Do your work self </pre> <hr></stringarray.length;></pre></stringarray1.length;>

În fragmentul de cod de mai sus, vedem că:

  • Când limita este 2, numărul de jetoane din matricea de șiruri este de două.
  • Când limita este -3, șirul specificat este împărțit în 2 jetoane. Include spațiile de sus.
  • Când limita este 0, șirul specificat este împărțit în 2 jetoane. În acest caz, spațiul final este omis.

Exemplu de șir delimitat prin conducte

Împărțirea unui șir delimitat de pipe (|) este puțin complicată. Deoarece pipe-ul este un caracter special în expresia regulată Java.

Să creăm un șir delimitat de țeavă și să-l împărțim după țeavă.

SplitStringExample5.java

cadru de colecție java
 public class SplitStringExample5 { public static void main(String args[]) { //defining a String object String s = &apos;Life|is|your|creation&apos;; //split string delimited by comma String[] stringarray = s.split(&apos;|&apos;); //we can use dot, whitespace, any character //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> L i f e | i s | y o u r | c r e a t i o n </pre> <p>In the above example, we see that it does not produce the same output as other delimiter yields. It should produce an array of tokens, <strong>life, yours,</strong> and <strong>creation</strong> , but it is not. It gives the result, as we have seen in the output above.</p> <p>The reason behind it that the regular expression engine interprets the pipe delimiter as a <strong>Logical OR operator</strong> . The regex engine splits the String on empty String.</p> <p>In order to resolve this problem, we must <strong>escape</strong> the pipe character when passed to the split() method. We use the following statement to escape the pipe character:</p> <pre> String[] stringarray = s.split(&apos;\|&apos;); </pre> <p>Add a pair of <strong>backslash (\)</strong> before the delimiter to escape the pipe. After doing the changes in the above program, the regex engine interprets the pipe character as a delimiter.</p> <p>Another way to escape the pipe character is to put the pipe character inside a pair of square brackets, as shown below. In the Java regex API, the pair of square brackets act as a character class.</p> <pre> String[] stringarray = s.split(&apos;[|]&apos;); </pre> <p>Both the above statements yield the following output:</p> <p> <strong>Output:</strong> </p> <pre> Life is your creation </pre> <h3>Using StringTokenizer Class</h3> <p>Java <strong>StringTokenizer</strong> is a legacy class that is defined in java.util package. It allows us to split the string into tokens. It is not used by the programmer because the split() method of the String class does the same work. So, the programmer prefers the split() method instead of the StringTokenizer class. We use the following two methods of the class:</p> <p> <strong>StringTokenizer.hasMoreTokens()</strong> </p> <p>The method iterates over the string and checks if there are more tokens available in the tokenizer string. It returns true if there is one token is available in the string after the current position, else returns false. It internally calls the <strong>nextToken()</strong> method if it returns true and the nextToken() method returns the token.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean hasMoreTokens() </pre> <p> <strong>StringTokenizer.nextToken()</strong> </p> <p>It returns the next token from the string tokenizer. It throws <strong>NoSuchElementException</strong> if the tokens are not available in the string tokenizer.</p> <p> <strong>Syntax:</strong> </p> <pre> public String nextToken() </pre> <p>Let&apos;s create a program that splits the string using the StringTokenizer class.</p> <p> <strong>SplitStringExample6.java</strong> </p> <pre> import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = &apos;Welcome/to/Javatpoint&apos;; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, &apos;/&apos;); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Welcome to Javatpoint </pre> <h2>Using Scanner.useDelimiter() Method</h2> <p>Java <strong>Scanner</strong> class provides the <strong>useDelimiter()</strong> method to split the string into tokens. There are two variants of the useDelimiter() method:</p> <ul> <li>useDelimiter(Pattern pattern)</li> <li>useDelimiter(String pattern)</li> </ul> <h3>useDelimiter(Pattern pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(Pattern pattern) </pre> <h3>useDelimiter(String pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to a pattern that constructs from the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(String pattern) </pre> <h4>Note: Both the above methods behave in the same way, as invoke the useDelimiter(Pattern.compile(pattern)).</h4> <p>In the following program, we have used the useDelimiter() method to split the string.</p> <p> <strong>SplitStringExample7.java</strong> </p> <pre> import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner(&apos;Do/your/work/self&apos;); //Initialize the string delimiter scan.useDelimiter(&apos;/&apos;); //checks if the tokenized Strings has next token while(scan.hasNext()) { //prints the next token System.out.println(scan.next()); } //closing the scanner scan.close(); } } </pre> <p> <strong>Output:</strong> </p> <pre> Do your work self </pre> <hr></stringarray.length;>

În exemplul de mai sus, vedem că nu produce aceeași ieșire ca și alte randamente de delimitare. Ar trebui să producă o serie de jetoane, viata, a ta, și creare , dar nu este. Oferă rezultatul, așa cum am văzut în rezultatul de mai sus.

Motivul din spatele lui că motorul de expresii regulate interpretează delimitatorul conductei ca a Operator logic SAU . Motorul regex împarte șirul pe șirul gol.

Pentru a rezolva această problemă, trebuie evadare caracterul pipe atunci când este trecut la metoda split(). Folosim următoarea declarație pentru a scăpa de caracterul pipe:

 String[] stringarray = s.split(&apos;\|&apos;); 

Adăugați o pereche de bară oblică inversă (\) înaintea delimitatorului pentru a scăpa de conductă. După efectuarea modificărilor în programul de mai sus, motorul regex interpretează caracterul pipe ca un delimitator.

O altă modalitate de a scăpa de caracterul pipe este să puneți caracterul pipe într-o pereche de paranteze pătrate, așa cum se arată mai jos. În API-ul Java regex, perechea de paranteze pătrate acționează ca o clasă de caractere.

 String[] stringarray = s.split(&apos;[|]&apos;); 

Ambele afirmații de mai sus produc următoarele rezultate:

Ieșire:

 Life is your creation 

Utilizarea clasei StringTokenizer

Java StringTokenizer este o clasă moștenită care este definită în pachetul java.util. Ne permite să împărțim șirul în jetoane. Nu este folosit de programator deoarece metoda split() a clasei String face aceeași activitate. Deci, programatorul preferă metoda split() în loc de clasa StringTokenizer. Folosim următoarele două metode ale clasei:

StringTokenizer.hasMoreTokens()

Metoda iterează peste șir și verifică dacă există mai multe jetoane disponibile în șirul de tokenizer. Returnează adevărat dacă există un simbol disponibil în șir după poziția curentă, altfel returnează false. Acesta numește intern nextToken() metoda dacă returnează adevărat și metoda nextToken() returnează simbolul.

Găsește-mi iPhone-ul de pe Android

Sintaxă:

 public boolean hasMoreTokens() 

StringTokenizer.nextToken()

Returnează următorul token de la tokenizer-ul șir. Aruncă NoSuchElementException dacă jetoanele nu sunt disponibile în tokenizer-ul șir.

Sintaxă:

 public String nextToken() 

Să creăm un program care împarte șirul folosind clasa StringTokenizer.

SplitStringExample6.java

 import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = &apos;Welcome/to/Javatpoint&apos;; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, &apos;/&apos;); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } } 

Ieșire:

 Welcome to Javatpoint 

Folosind metoda Scanner.useDelimiter().

Java Scanner clasa oferă useDelimiter() metodă de a împărți șirul în jetoane. Există două variante ale metodei useDelimiter():

  • useDelimiter (model de model)
  • useDelimiter (model șir)

useDelimiter (model de model)

Metoda setează modelul de delimitare al scanerului la șirul specificat. Analizează un model de delimitare ca argument. Acesta returnează scanerul.

Sintaxă:

 public Scanner useDelimiter(Pattern pattern) 

useDelimiter (model șir)

Metoda setează modelul de delimitare al scanerului la un model care se construiește din șirul specificat. Analizează un model de delimitare ca argument. Acesta returnează scanerul.

Sintaxă:

 public Scanner useDelimiter(String pattern) 

Notă: Ambele metode de mai sus se comportă în același mod, deoarece invocă useDelimiter(Pattern.compile(pattern)).

În următorul program, am folosit metoda useDelimiter() pentru a împărți șirul.

SplitStringExample7.java

 import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner(&apos;Do/your/work/self&apos;); //Initialize the string delimiter scan.useDelimiter(&apos;/&apos;); //checks if the tokenized Strings has next token while(scan.hasNext()) { //prints the next token System.out.println(scan.next()); } //closing the scanner scan.close(); } } 

Ieșire:

 Do your work self