logo

Kako razdeliti niz v Javi z ločilom?

V Javi, razcepna vrvica je pomembna in običajno uporabljena operacija pri kodiranju. Java ponuja več načinov za razdeli vrvico . Toda najpogostejši način je uporaba metoda split(). razreda String. V tem razdelku se bomo naučili kako razdeliti niz v Javi z ločilom. Poleg tega se bomo naučili tudi nekaterih drugih metod za razdelitev niza, kot je uporaba razreda StringTokenizer, Metoda Scanner.useDelimiter(). . Preden preidemo na temo, se razumejmo kaj je ločilo.

Kaj je ločilo?

notri Java , ločila so znaki, ki razdelijo (ločijo) niz na žetone. Java nam omogoča, da kot ločilo določimo poljubne znake. Obstaja veliko metod razdelitve nizov, ki jih ponuja Java, ki uporabljajo presledek kot ločilo. The ločilo presledkov ali je privzeto ločilo v Javi.

Preden preidemo na program, razumejmo koncept niza.

Niz je sestavljen iz dveh vrst besedila, ki sta žetoni in ločila. Žetoni so besede, ki so smiselne, ločila pa so znaki, ki delijo ali ločujejo žetone. Razumejmo to skozi primer.

Za razumevanje ločilo v Javi , moramo biti prijateljski z Regularni izraz Java . Potreben je, ko se ločilo uporablja kot poseben znak v regularnih izrazih, kot sta (.) in (|).

Primer ločila

Vrvica: Javatpoint je najboljše spletno mesto za učenje novih tehnologij.

V zgornjem nizu so žetoni, Javatpoint je najboljša spletna stran za učenje novih tehnologij , ločila pa so presledki med obema žetonoma.

Kako razdeliti niz v Javi z ločilom?

Java ponuja naslednji način za razdelitev niza na žetone:

Uporaba metode Scanner.next().

Je metoda razreda Scanner. Najde in vrne naslednji žeton iz skenerja. Niz razdeli na žetone z ločilom presledkov. Celoten žeton je identificiran z vnosom, ki se ujema z vzorcem ločila.

Sintaksa:

 public String next(); 

Vrže NoSuchElementException če naslednji žeton ni na voljo. Prav tako meče IllegalStateException če je vhodni skener zaprt.

Ustvarimo program, ki razdeli objekt niza z uporabo metode next(), ki uporablja presledke za razdelitev niza na žetone.

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(); } } } 

Izhod:

igra pigeon android
 Javatpoint is the best website to learn new technologies 

V zgornjem programu je treba opaziti, da smo v konstruktorju razreda Scanner namesto posredovanja System.in posredovali nizovno spremenljivko str. To smo storili, ker moramo pred manipulacijo niza prebrati niz.

Uporaba metode String.split().

The razdeli () metoda Vrvica razred se uporablja za razdelitev niza v matriko objektov String na podlagi podanega ločila, ki se ujema z regularnim izrazom. Na primer, razmislite o naslednjem nizu:

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

Zgornji niz je ločen z vejicami. Zgornji niz lahko razdelimo z naslednjim izrazom:

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

Zgornji izraz razdeli niz na žetone, ko so žetoni ločeni z določeno ločilno vejico (,). Navedeni niz se je razdelil na naslednje objekte niza:

 Welcome to the word of technology 

Obstajata dve različici metod split():

jquery ob kliku
  • razdeli (niz regularnega izraza)
  • split (reg. izraz niza, omejitev int)

String.split(niz regularnega izraza)

Razdeli niz glede na podani regularni izraz regularnega izraza. Uporabimo lahko piko (.), presledek (), vejico (,) in poljuben znak (na primer z, a, g, l itd.)

Sintaksa:

 public String[] split(String regex) 

Metoda razčleni regularni izraz ločila kot argument. Vrne matriko objektov String. Vrže PatternSyntaxException če ima razčlenjeni regularni izraz neveljavno sintakso.

Uporabimo metodo split() in razdelimo niz z vejico.

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;>

V zgornjem primeru je objekt niza razmejen z vejico. Metoda split() razdeli niz, ko najde vejico kot ločilo.

Oglejmo si še en primer, v katerem bomo za razdelitev niza uporabili več ločil.

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(regularni izraz niza, omejitev int)

Omogoča nam razdelitev niza, določenega z ločilom, vendar na omejeno število žetonov. Metoda sprejme dva parametra regex (regularni izraz za razmejitev) in limit. Parameter omejitve se uporablja za nadzor števila uporabljenih vzorcev, ki vplivajo na nastalo matriko. Vrne matriko objektov String, izračunanih z razdelitvijo podanega niza glede na parameter limit.

Obstaja majhna razlika med različico metod split() v tem, da omejuje število žetonov, vrnjenih po priklicu metode.

Sintaksa:

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

Vrže PatternSyntaxException če ima razčlenjeni regularni izraz neveljavno sintakso.

Parameter limita je lahko pozitiven, negativen ali enak limitu.

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;>

V zgornjem delčku kode vidimo, da:

  • Ko je omejitev 2, je število žetonov v nizu dva.
  • Ko je omejitev -3, se podani niz razdeli na 2 žetona. Vključuje presledke na koncu.
  • Ko je omejitev 0, se podani niz razdeli na 2 žetona. V tem primeru je presledek na koncu izpuščen.

Primer niza, ločenega s črto

Razdelitev niza, ločenega s črto (|), je nekoliko težavna. Ker je cev poseben znak v regularnem izrazu Jave.

Ustvarimo niz, ločen s črto, in ga razdelimo s črto.

SplitStringExample5.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;>

V zgornjem primeru vidimo, da ne ustvari enakega izhoda kot drugi deliliter. Ustvariti mora niz žetonov, življenje, tvoje, in ustvarjanje , vendar ni. Daje rezultat, kot smo videli v zgornjem rezultatu.

Razlog za to je, da mehanizem regularnih izrazov ločilo navpične cevi razlaga kot a Logični operator ALI . Mehanizem regularnih izrazov razdeli niz na prazen niz.

Da bi rešili ta problem, moramo pobegniti cevni znak, ko je posredovan metodi split(). Za umik znaka cevi uporabimo naslednji stavek:

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

Dodajte par poševnica nazaj (\) pred ločilom za izhod iz cevi. Po izvedbi sprememb v zgornjem programu mehanizem regularnih izrazov interpretira cev kot ločilo.

Drug način za izhod iz navpičnega znaka je, da postavite navpičen znak znotraj para oglatih oklepajev, kot je prikazano spodaj. V API-ju za regex Java par oglatih oklepajev deluje kot razred znakov.

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

Oba zgornja stavka dajeta naslednje rezultate:

Izhod:

 Life is your creation 

Uporaba razreda StringTokenizer

Java StringTokenizer je starejši razred, ki je definiran v paketu java.util. Omogoča nam razdelitev niza na žetone. Programer ga ne uporablja, ker metoda split() razreda String opravlja enako delo. Torej ima programer raje metodo split() namesto razreda StringTokenizer. Uporabljamo naslednji dve metodi razreda:

StringTokenizer.hasMoreTokens()

algoritem združevanja

Metoda ponovi niz in preveri, ali je v nizu tokenizerja na voljo več žetonov. Vrne true, če je v nizu za trenutnim položajem na voljo en žeton, sicer vrne false. Interno kliče nextToken() metoda, če vrne true in metoda nextToken() vrne žeton.

Sintaksa:

 public boolean hasMoreTokens() 

StringTokenizer.nextToken()

Vrne naslednji žeton iz tokenizatorja nizov. Vrže NoSuchElementException če žetoni niso na voljo v tokenizerju nizov.

stoji

Sintaksa:

 public String nextToken() 

Ustvarimo program, ki razdeli niz z uporabo razreda 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()); } } } 

Izhod:

 Welcome to Javatpoint 

Uporaba metode Scanner.useDelimiter().

Java Skener razred zagotavlja useDelimiter() metoda za razdelitev niza na žetone. Obstajata dve različici metode useDelimiter():

  • useDelimiter(vzorec vzorca)
  • useDelimiter(Vzorec niza)

useDelimiter(vzorec vzorca)

Metoda nastavi razmejitveni vzorec optičnega bralnika na podani niz. Ločevalni vzorec razčleni kot argument. Vrne skener.

Sintaksa:

 public Scanner useDelimiter(Pattern pattern) 

useDelimiter(Vzorec niza)

Metoda nastavi razmejitveni vzorec optičnega bralnika na vzorec, ki je sestavljen iz navedenega niza. Ločevalni vzorec razčleni kot argument. Vrne skener.

Sintaksa:

 public Scanner useDelimiter(String pattern) 

Opomba: obe zgornji metodi se obnašata na enak način kot priklic useDelimiter(Pattern.compile(pattern)).

V naslednjem programu smo za razdelitev niza uporabili metodo useDelimiter().

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(); } } 

Izhod:

 Do your work self