logo

Как да разделя низ в Java с разделител?

В Java, разделяне на низ е важна и обикновено използвана операция при кодиране. Java предоставя множество начини за разделете низа . Но най-често срещаният начин е да използвате метод split(). от класа String. В този раздел ще научим как да разделя низ в Java с разделител. Заедно с това ще научим и някои други методи за разделяне на низа, като използването на клас StringTokenizer, Метод Scanner.useDelimiter(). . Преди да преминем към темата, нека разберем какво е разделител.

Какво е разделител?

в Java , разделители са знаците, които разделят (разделят) низа на токени. Java ни позволява да дефинираме всякакви символи като разделител. Има много методи за разделяне на низове, предоставени от Java, които използват знак за празно пространство като разделител. The разделител за интервали е разделител по подразбиране в Java.

Преди да преминем към програмата, нека разберем концепцията за низ.

Низът е съставен от два типа текст, които са токени и разделители. Токените са думите, които имат смисъл, а разделителите са знаците, които разделят или разделят токените. Нека го разберем чрез пример.

За да разберете разделител в Java , трябва да сме приятелски настроени към регулярен израз на Java . Необходимо е, когато разделителят се използва като специален знак в регулярните изрази, като (.) и (|).

Пример за разделител

низ: Javatpoint е най-добрият уебсайт за изучаване на нови технологии.

В горния низ токените са, Javatpoint е най-добрият уебсайт за научаване на нови технологии , а разделителите са бели интервали между двата жетона.

Как да разделя низ в Java с разделител?

Java предоставя следния начин за разделяне на низ на токени:

Използване на метода Scanner.next().

Това е методът на класа Scanner. Той намира и връща следващия токен от скенера. Той разделя низа на токени чрез разделител за интервали. Пълният токен се идентифицира чрез входа, който съответства на шаблона на разделителя.

Синтаксис:

 public String next(); 

Хвърля се NoSuchElementException ако следващият токен не е наличен. Освен това хвърля IllegalStateException ако входният скенер е затворен.

Нека създадем програма, която разделя низов обект, използвайки метода next(), който използва интервали, за да раздели низа на токени.

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

Изход:

име на град в САЩ
 Javatpoint is the best website to learn new technologies 

В горната програма трябва да се отбележи, че в конструктора на класа Scanner, вместо да подадем System.in, сме предали низова променлива str. Направихме го, защото преди да манипулираме низа, трябва да го прочетем.

Използване на метода String.split().

The разделяне () метод на низ клас се използва за разделяне на низ в масив от String обекти въз основа на посочения разделител, който съответства на регулярния израз. Например, разгледайте следния низ:

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

Горният низ е разделен със запетаи. Можем да разделим горния низ, като използваме следния израз:

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

Горният израз разделя низа на токени, когато токените са разделени с определен разделителен знак запетая (,). Посоченият низ се разделя на следните низови обекти:

 Welcome to the word of technology 

Има два варианта на методите split():

  • разделяне (регулярен израз на низ)
  • split(регулярен израз на низ, ограничение на int)

String.split(регулярен израз на низ)

Той разделя низа според определен регулярен израз на регулярен израз. Можем да използваме точка (.), интервал (), запетая (,) и всеки знак (като z, a, g, l и т.н.)

Синтаксис:

 public String[] split(String regex) 

Методът анализира разделителен регулярен израз като аргумент. Връща масив от String обекти. Хвърля се PatternSyntaxException ако анализираният регулярен израз има невалиден синтаксис.

Нека използваме метода split() и разделим низа със запетая.

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

В горния пример низовият обект е разделен със запетая. Методът split() разделя низа, когато намери запетая като разделител.

Нека видим друг пример, в който ще използваме множество разделители, за да разделим низа.

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(регулярен израз на низ, ограничение на int)

Това ни позволява да разделим низ, определен от разделител, но на ограничен брой токени. Методът приема два параметъра regex (ограничаващ регулярен израз) и limit. Параметърът limit се използва за контролиране на броя на прилагането на модела, който засяга резултантния масив. Той връща масив от String обекти, изчислен чрез разделяне на дадения низ според параметъра limit.

Има малка разлика между варианта на методите split(), че ограничава броя на токените, върнати след извикване на метода.

съединения и видове съединения

Синтаксис:

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

Хвърля се PatternSyntaxException ако анализираният регулярен израз има невалиден синтаксис.

Граничният параметър може да бъде положителен, отрицателен или равен на лимита.

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

В горния кодов фрагмент виждаме, че:

  • Когато ограничението е 2, броят на токените в низовия масив е два.
  • Когато ограничението е -3, посоченият низ се разделя на 2 токена. Включва завършващите интервали.
  • Когато ограничението е 0, указаният низ се разделя на 2 токена. В този случай интервалът в края се пропуска.

Пример за низ, разделен с тръба

Разделянето на низ, разделен с тръба (|), е малко сложно. Тъй като тръбата е специален знак в регулярния израз на Java.

Нека създадем низ, разделен с тръба и да я разделим по тръба.

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

В горния пример виждаме, че той не произвежда същия изход като другите разделители. Трябва да създаде масив от токени, живот, твой, и създаване , но не е. Той дава резултата, както видяхме в резултата по-горе.

Причината за това е, че механизмът за регулярен израз интерпретира разделителя на тръбата като a Логически оператор ИЛИ . Механизмът за регулярни изрази разделя низа на празен низ.

За да разрешим този проблем, трябва бягство символът за тръба, когато се предава на метода split(). Използваме следния оператор, за да избегнем символа за тръба:

форматиране на низове
 String[] stringarray = s.split(&apos;\|&apos;); 

Добавете чифт наклонена черта (\) преди разделителя, за да излезете от тръбата. След извършване на промените в горната програма, машината за регулярни изрази интерпретира символа за тръба като разделител.

Друг начин за избягване на символа за тръба е да поставите знака за тръба в чифт квадратни скоби, както е показано по-долу. В Java regex API двойката квадратни скоби действат като символен клас.

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

И двете горни твърдения дават следния резултат:

Изход:

 Life is your creation 

Използване на клас StringTokenizer

Java StringTokenizer е наследен клас, който е дефиниран в пакета java.util. Това ни позволява да разделим низа на токени. Не се използва от програмиста, защото методът split() на класа String върши същата работа. И така, програмистът предпочита метода split() вместо класа StringTokenizer. Използваме следните два метода на класа:

StringTokenizer.hasMoreTokens()

Методът итерира през низа и проверява дали има повече налични токени в низа на токенизатора. Връща true, ако има един наличен токен в низа след текущата позиция, в противен случай връща false. Той вътрешно нарича nextToken() ако връща true и методът nextToken() връща токена.

Синтаксис:

колко седмици на месец
 public boolean hasMoreTokens() 

StringTokenizer.nextToken()

Той връща следващия токен от токенизатора на низове. Хвърля се NoSuchElementException ако токените не са налични в токенизатора на низове.

Синтаксис:

 public String nextToken() 

Нека създадем програма, която разделя низа с помощта на класа 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()); } } } 

Изход:

 Welcome to Javatpoint 

Използване на метода Scanner.useDelimiter().

Java Скенер клас осигурява useDelimiter() метод за разделяне на низа на токени. Има два варианта на метода useDelimiter():

  • useDelimiter(образец на образец)
  • useDelimiter (образец на низ)

useDelimiter(образец на образец)

Методът задава шаблона за разделяне на скенера на посочения низ. Той анализира разделителен модел като аргумент. Връща скенера.

Синтаксис:

 public Scanner useDelimiter(Pattern pattern) 

useDelimiter (образец на низ)

Методът задава шаблона за разделяне на скенера на модел, който се конструира от посочения низ. Той анализира разделителен модел като аргумент. Връща скенера.

Синтаксис:

 public Scanner useDelimiter(String pattern) 

Забележка: И двата метода по-горе се държат по същия начин, като извикват useDelimiter(Pattern.compile(pattern)).

В следващата програма сме използвали метода 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(); } } 

Изход:

 Do your work self