A Java, corda dividida és una operació important i que s'utilitza habitualment a l'hora de codificar. Java ofereix diverses maneres de fer-ho dividir la corda . Però la manera més habitual és utilitzar el mètode split(). de la classe String. En aquest apartat, aprendrem com dividir una cadena a Java amb un delimitador. Juntament amb això, també aprendrem alguns altres mètodes per dividir la cadena, com l'ús de la classe StringTokenizer, Mètode Scanner.useDelimiter(). . Abans de passar al tema, entenem-ho què és el delimitador.
Què és un delimitador?
En Java , delimitadors són els caràcters que divideixen (separen) la cadena en fitxes. Java ens permet definir qualsevol caràcter com a delimitador. Hi ha molts mètodes de divisió de cadenes proporcionats per Java que utilitzen el caràcter d'espai en blanc com a delimitador. El delimitador d'espais en blanc és el delimitador per defecte en Java.
Abans de passar al programa, entenem el concepte de cadena.
La cadena està formada per dos tipus de text que són fitxes i delimitadors. Les fitxes són les paraules que tenen sentit i els delimitadors són els caràcters que divideixen o separen les fitxes. Entenem-ho amb un exemple.
Per entendre el delimitador en Java , hem de fer amics amb el Expressió regular de Java . És necessari quan el delimitador s'utilitza com a caràcter especial en les expressions regulars, com (.) i (|).
Exemple de delimitador
Cadena: Javatpoint és el millor lloc web per aprendre noves tecnologies.
A la cadena anterior, les fitxes són, Javatpoint és el millor lloc web per aprendre noves tecnologies , i els delimitadors ho són espais en blanc entre les dues fitxes.
Com dividir una cadena a Java amb delimitador?
Java proporciona la següent manera de dividir una cadena en testimonis:
- Utilitzant el mètode Scanner.next().
- Utilitzant el mètode String.split().
- Utilitzant la classe StringTokenizer
Utilitzant el mètode Scanner.next().
És el mètode de la classe Scanner. Troba i torna el següent testimoni de l'escàner. Divideix la cadena en fitxes mitjançant un delimitador d'espais en blanc. El testimoni complet s'identifica per l'entrada que coincideix amb el patró delimitador.
Sintaxi:
public String next();
Es tira NoSuchElementException si el següent testimoni no està disponible. També llença IllegalStateException si l'escàner d'entrada està tancat.
Creem un programa que divideixi un objecte de cadena mitjançant el mètode next() que utilitza espais en blanc per dividir la cadena en fitxes.
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(); } } }
Sortida:
excepció de llançament de java
Javatpoint is the best website to learn new technologies
En el programa anterior, cal observar que al constructor de la classe Scanner en lloc de passar el System.in hem passat una variable de cadena str. Ho hem fet perquè abans de manipular la cadena, hem de llegir la cadena.
Utilitzant el mètode String.split().
El dividir () mètode de la Corda classe s'utilitza per dividir una cadena en una matriu d'objectes String en funció del delimitador especificat que coincideix amb l'expressió regular. Per exemple, considereu la cadena següent:
String str= 'Welcome,to,the,word,of,technology';
La cadena anterior està separada per comes. Podem dividir la cadena anterior utilitzant l'expressió següent:
String[] tokens=s.split(',');
L'expressió anterior divideix la cadena en testimonis quan els testimonis estan separats per un caràcter delimitador especificat per coma (,). La cadena especificada es divideix en els següents objectes de cadena:
Welcome to the word of technology
Hi ha dues variants dels mètodes split():
- split(String regex)
- split(String regex, límit int)
String.split(String regex)
Divideix la cadena segons l'expressió regular especificada. Podem utilitzar un punt (.), espai ( ), coma (,) i qualsevol caràcter (com z, a, g, l, etc.)
Sintaxi:
public String[] split(String regex)
El mètode analitza una expressió regular delimitadora com a argument. Retorna una matriu d'objectes String. Es tira PatternSyntaxException si l'expressió regular analitzada té una sintaxi no vàlida.
algorisme de Bellford
Utilitzem el mètode split() i dividim la cadena amb una coma.
SplitStringExample2.java
public class SplitStringExample2 { public static void main(String args[]) { //defining a String object String s = 'Life,is,your,creation'; //split string delimited by comma String[] stringarray = s.split(','); //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'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 = 'If you don't like something, change.it.'; //split string by multiple delimiters String[] stringarray = s.split('[, . ']+'); //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 = '468-567-7388'; String str2 = 'Life,is,your,creation'; String str3 = 'Hello! how are you?'; String[] stringarray1 = str1.split('8',2); System.out.println('When the limit is positive:'); System.out.println('Number of tokens: '+stringarray1.length); for(int i=0; i<stringarray1.length; i++) { system.out.println(stringarray1[i]); } string[] stringarray2="str2.split('y',-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('!',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'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 = 'Life|is|your|creation'; //split string delimited by comma String[] stringarray = s.split('|'); //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('\|'); </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('[|]'); </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'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 = 'Welcome/to/Javatpoint'; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, '/'); //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'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'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('Do/your/work/self'); //Initialize the string delimiter scan.useDelimiter('/'); //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;>
A l'exemple anterior, l'objecte de cadena està delimitat per una coma. El mètode split() divideix la cadena quan troba la coma com a delimitador.
Vegem un altre exemple en què utilitzarem diversos delimitadors per dividir la cadena.
SplitStringExample3.java
public class SplitStringExample3 { public static void main(String args[]) { //defining a String object String s = 'If you don't like something, change.it.'; //split string by multiple delimiters String[] stringarray = s.split('[, . ']+'); //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 = '468-567-7388'; String str2 = 'Life,is,your,creation'; String str3 = 'Hello! how are you?'; String[] stringarray1 = str1.split('8',2); System.out.println('When the limit is positive:'); System.out.println('Number of tokens: '+stringarray1.length); for(int i=0; i<stringarray1.length; i++) { system.out.println(stringarray1[i]); } string[] stringarray2="str2.split('y',-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('!',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'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 = 'Life|is|your|creation'; //split string delimited by comma String[] stringarray = s.split('|'); //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('\|'); </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('[|]'); </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'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 = 'Welcome/to/Javatpoint'; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, '/'); //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'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'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('Do/your/work/self'); //Initialize the string delimiter scan.useDelimiter('/'); //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, límit int)
Ens permet dividir la cadena especificada pel delimitador però en un nombre limitat de fitxes. El mètode accepta dos paràmetres regex (una expressió regular delimitadora) i limit. El paràmetre de límit s'utilitza per controlar el nombre de vegades que s'aplica el patró que afecta la matriu resultant. Retorna una matriu d'objectes String calculats dividint la cadena donada segons el paràmetre de límit.
Hi ha una lleugera diferència entre la variant dels mètodes split() que limita el nombre de fitxes retornades després d'invocar el mètode.
Sintaxi:
public String[] split(String regex, int limit)
Es tira PatternSyntaxException si l'expressió regular analitzada té una sintaxi no vàlida.
El paràmetre límit pot ser positiu, negatiu o igual al límit.
SplitStringExample4.java
public class SplitStringExample4 { public static void main(String args[]) { String str1 = '468-567-7388'; String str2 = 'Life,is,your,creation'; String str3 = 'Hello! how are you?'; String[] stringarray1 = str1.split('8',2); System.out.println('When the limit is positive:'); System.out.println('Number of tokens: '+stringarray1.length); for(int i=0; i<stringarray1.length; i++) { system.out.println(stringarray1[i]); } string[] stringarray2="str2.split('y',-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('!',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'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 = 'Life|is|your|creation'; //split string delimited by comma String[] stringarray = s.split('|'); //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('\|'); </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('[|]'); </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'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 = 'Welcome/to/Javatpoint'; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, '/'); //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'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'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('Do/your/work/self'); //Initialize the string delimiter scan.useDelimiter('/'); //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;>
Al fragment de codi anterior, veiem que:
- Quan el límit és 2, el nombre de fitxes a la matriu de cadenes és de dos.
- Quan el límit és -3, la cadena especificada es divideix en 2 fitxes. Inclou els espais posteriors.
- Quan el límit és 0, la cadena especificada es divideix en 2 fitxes. En aquest cas, s'omet l'espai al final.
Exemple de cadena delimitada per canonades
Dividir una cadena delimitada per pipe (|) és una mica complicat. Com que la canonada és un caràcter especial en l'expressió regular de Java.
Creem una cadena delimitada per canonada i dividim-la per canonada.
SplitStringExample5.java
public class SplitStringExample5 { public static void main(String args[]) { //defining a String object String s = 'Life|is|your|creation'; //split string delimited by comma String[] stringarray = s.split('|'); //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('\|'); </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('[|]'); </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'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 = 'Welcome/to/Javatpoint'; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, '/'); //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'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'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('Do/your/work/self'); //Initialize the string delimiter scan.useDelimiter('/'); //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 l'exemple anterior, veiem que no produeix la mateixa sortida que altres rendiments de delimitadors. Hauria de produir una sèrie de fitxes, vida, teva, i creació , però no ho és. Dóna el resultat, com hem vist a la sortida anterior.
El motiu que hi ha darrere és que el motor d'expressions regulars interpreta el delimitador de canonades com a Operador OR lògic . El motor d'expressió regular divideix la cadena en una cadena buida.
Per resoldre aquest problema, hem de escapar el caràcter pipe quan es passa al mètode split(). Utilitzem la següent instrucció per escapar del caràcter de pipe:
String[] stringarray = s.split('\|');
Afegeix un parell de barra invertida (\) abans del delimitador per escapar del tub. Després de fer els canvis al programa anterior, el motor d'expressions regulars interpreta el caràcter pipe com a delimitador.
Una altra manera d'escapar del caràcter de tub és posar el caràcter de tub dins d'un parell de claudàtors, com es mostra a continuació. A l'API d'expressió regular de Java, el parell de claudàtors actuen com a classe de caràcters.
String[] stringarray = s.split('[|]');
Les dues declaracions anteriors donen la següent sortida:
Sortida:
cadena en java
Life is your creation
Utilitzant la classe StringTokenizer
Java StringTokenizer és una classe heretada que es defineix al paquet java.util. Ens permet dividir la cadena en fitxes. El programador no l'utilitza perquè el mètode split() de la classe String fa el mateix treball. Per tant, el programador prefereix el mètode split() en lloc de la classe StringTokenizer. Utilitzem els dos mètodes següents de la classe:
StringTokenizer.hasMoreTokens()
El mètode itera sobre la cadena i comprova si hi ha més fitxes disponibles a la cadena del tokenizer. Retorna true si hi ha un testimoni disponible a la cadena després de la posició actual, en cas contrari retorna false. Internament anomena el nextToken() mètode si retorna cert i el mètode nextToken() retorna el testimoni.
Sintaxi:
public boolean hasMoreTokens()
StringTokenizer.nextToken()
Retorna el següent testimoni del tokenitzador de cadena. Es tira NoSuchElementException si les fitxes no estan disponibles al tokenizer de cadena.
Sintaxi:
public String nextToken()
Creem un programa que divideixi la cadena utilitzant la classe StringTokenizer.
SplitStringExample6.java
import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = 'Welcome/to/Javatpoint'; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, '/'); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } }
Sortida:
Welcome to Javatpoint
Utilitzant el mètode Scanner.useDelimiter().
Java Escàner classe proporciona el useDelimiter() mètode per dividir la cadena en fitxes. Hi ha dues variants del mètode useDelimiter():
- useDelimiter (patró de patró)
- useDelimiter (patró de cadena)
useDelimiter (patró de patró)
El mètode estableix el patró delimitador de l'escàner a la cadena especificada. Analitza un patró delimitador com a argument. Torna l'escàner.
Sintaxi:
public Scanner useDelimiter(Pattern pattern)
useDelimiter (patró de cadena)
El mètode estableix el patró delimitador de l'escàner en un patró que es construeix a partir de la cadena especificada. Analitza un patró delimitador com a argument. Torna l'escàner.
Sintaxi:
public Scanner useDelimiter(String pattern)
Nota: els dos mètodes anteriors es comporten de la mateixa manera, ja que invoquen useDelimiter(Pattern.compile(pattern)).
Al programa següent, hem utilitzat el mètode useDelimiter() per dividir la cadena.
alfabet per nombre
SplitStringExample7.java
import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner('Do/your/work/self'); //Initialize the string delimiter scan.useDelimiter('/'); //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(); } }
Sortida:
Do your work self