logo

Hoe een string in Java te splitsen met scheidingsteken?

Op Java, splitsende snaar is een belangrijke en meestal gebruikte bewerking bij het coderen. Java biedt meerdere manieren om splits de string . Maar de meest gebruikelijke manier is om de split()-methode van de String-klasse. In dit gedeelte zullen we leren hoe je een string in Java splitst met een scheidingsteken. Daarnaast zullen we ook enkele andere methoden leren om de string te splitsen, zoals het gebruik van de StringTokenizer-klasse, Scanner.useDelimiter()-methode . Voordat we naar het onderwerp gaan, laten we het begrijpen wat is een scheidingsteken.

Wat is een scheidingsteken?

In Java , scheidingstekens zijn de karakters die de string in tokens splitsen (scheiden). Met Java kunnen we elk teken als scheidingsteken definiëren. Er zijn veel methoden voor het splitsen van tekenreeksen die door Java worden aangeboden, waarbij spaties als scheidingsteken worden gebruikt. De scheidingsteken voor witruimte is de standaard scheidingsteken op Java.

Voordat we naar het programma gaan, moeten we eerst het concept van string begrijpen.

De tekenreeks bestaat uit twee typen tekst Munten En scheidingstekens. De tokens zijn de woorden die betekenisvol zijn, en de scheidingstekens zijn de tekens die de tokens splitsen of scheiden. Laten we het begrijpen aan de hand van een voorbeeld.

Om de te begrijpen scheidingsteken in Java , we moeten bevriend raken met de Reguliere Java-expressie . Dit is nodig wanneer het scheidingsteken wordt gebruikt als een speciaal teken in reguliere expressies, zoals (.) en (|).

Voorbeeld van scheidingsteken

Snaar: Javatpoint is de beste website om nieuwe technologieën te leren.

In de bovenstaande reeks zijn tokens: Javatpoint is de beste website om nieuwe technologieën te leren , en de scheidingstekens zijn witruimtes tussen de twee tokens.

Hoe een string in Java te splitsen met scheidingsteken?

Java biedt de volgende manier om een ​​string in tokens te splitsen:

Met behulp van de Scanner.next()-methode

Het is de methode van de klasse Scanner. Het vindt het volgende token van de scanner en retourneert het. Het splitst de string in tokens door middel van een witruimtescheidingsteken. Het volledige token wordt geïdentificeerd door de invoer die overeenkomt met het scheidingstekenpatroon.

Syntaxis:

 public String next(); 

Het gooit NoSuchElementException als het volgende token niet beschikbaar is. Het gooit ook IllegaleStateException als de invoerscanner gesloten is.

Laten we een programma maken dat een stringobject splitst met behulp van de next()-methode die witruimte gebruikt om de string in tokens te splitsen.

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

Uitgang:

1 van 1000
 Javatpoint is the best website to learn new technologies 

In het bovenstaande programma is het een punt om op te merken dat we in de constructor van de klasse Scanner in plaats van System.in een stringvariabele str hebben doorgegeven. We hebben dit gedaan omdat we, voordat we de string manipuleren, de string moeten lezen.

Met behulp van de String.split()-methode

De splitsen() werkwijze van de Snaar klas wordt gebruikt om een ​​string op te splitsen in een array van String-objecten op basis van het opgegeven scheidingsteken dat overeenkomt met de reguliere expressie. Beschouw bijvoorbeeld de volgende tekenreeks:

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

De bovenstaande tekenreeks wordt gescheiden door komma's. We kunnen de bovenstaande string splitsen door de volgende expressie te gebruiken:

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

De bovenstaande expressie splitst de tekenreeks in tokens wanneer de tokens worden gescheiden door een opgegeven scheidingsteken komma (,). De opgegeven tekenreeks is opgesplitst in de volgende tekenreeksobjecten:

 Welcome to the word of technology 

Er zijn twee varianten van de split()-methoden:

  • splitsen(tekenreeksregex)
  • split(String regex, int-limiet)

String.split(String-regex)

Het splitst de string volgens de gespecificeerde reguliere expressie-regex. We kunnen een punt (.), spatie ( ), komma (,) en elk teken (zoals z, a, g, l, enz.) gebruiken.

Syntaxis:

 public String[] split(String regex) 

De methode ontleedt een reguliere expressie met scheidingstekens als argument. Het retourneert een array met String-objecten. Het gooit PatroonSyntaxisUitzondering als de geparseerde reguliere expressie een ongeldige syntaxis heeft.

Laten we de methode split() gebruiken en de tekenreeks splitsen met een komma.

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

In het bovenstaande voorbeeld wordt het stringobject gescheiden door een komma. De methode split() splitst de tekenreeks wanneer de komma als scheidingsteken wordt gevonden.

Laten we nog een voorbeeld bekijken waarin we meerdere scheidingstekens gebruiken om de tekenreeks te splitsen.

uri versus url

SplitStringExample3.java

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

String.split(String regex, int-limiet)

Hiermee kunnen we de tekenreeks die is opgegeven door een scheidingsteken, splitsen in een beperkt aantal tokens. De methode accepteert twee parameters regex (een begrenzende reguliere expressie) en limit. De parameter limit wordt gebruikt om het aantal keren te bepalen dat het patroon wordt toegepast dat de resulterende array beïnvloedt. Het retourneert een array van String-objecten, berekend door de gegeven string te splitsen volgens de limit-parameter.

Er is een klein verschil tussen de variant van de split()-methoden, namelijk dat het aantal tokens wordt beperkt dat wordt geretourneerd na het aanroepen van de methode.

Syntaxis:

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

Het gooit PatroonSyntaxisUitzondering als de geparseerde reguliere expressie een ongeldige syntaxis heeft.

De limietparameter kan positief, negatief of gelijk aan de limiet zijn.

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

In het bovenstaande codefragment zien we dat:

  • Wanneer de limiet 2 is, is het aantal tokens in de stringarray twee.
  • Wanneer de limiet -3 is, wordt de opgegeven tekenreeks opgesplitst in 2 tokens. Het omvat de volgspaties.
  • Wanneer de limiet 0 is, wordt de opgegeven string opgesplitst in 2 tokens. In dit geval wordt de volgspatie weggelaten.

Voorbeeld van een door pijpen gescheiden string

Het splitsen van een snaar die wordt begrensd door een pijp (|) is een beetje lastig. Omdat de pipe een speciaal teken is in de reguliere Java-expressie.

Laten we een string maken die wordt begrensd door een pijp en deze splitsen door een pijp.

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

In het bovenstaande voorbeeld zien we dat het niet dezelfde uitvoer oplevert als andere scheidingstekenopbrengsten. Het zou een reeks tokens moeten produceren, leven, het jouwe, En creatie , maar het is niet. Het geeft het resultaat, zoals we in de bovenstaande uitvoer hebben gezien.

De reden hierachter dat de reguliere expressie-engine het pijpscheidingsteken interpreteert als een Logische OR-operator . De regex-engine splitst de String op een lege String.

Om dit probleem op te lossen, moeten we ontsnappen het pipe-teken wanneer het wordt doorgegeven aan de split()-methode. We gebruiken de volgende instructie om aan het pipe-teken te ontsnappen:

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

Voeg een paar toe backslash (\) vóór het scheidingsteken om uit de pijp te ontsnappen. Nadat de wijzigingen in het bovenstaande programma zijn aangebracht, interpreteert de regex-engine het pipe-teken als een scheidingsteken.

Een andere manier om aan het pijpteken te ontsnappen, is door het pijpteken tussen vierkante haakjes te plaatsen, zoals hieronder weergegeven. In de Java regex API fungeert het paar vierkante haakjes als een tekenklasse.

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

Beide bovenstaande verklaringen leveren de volgende uitvoer op:

Uitgang:

 Life is your creation 

StringTokenizer-klasse gebruiken

Java StringTokenizer is een oudere klasse die is gedefinieerd in het java.util-pakket. Hiermee kunnen we de string in tokens splitsen. Het wordt niet door de programmeur gebruikt omdat de methode split() van de klasse String hetzelfde werk doet. De programmeur geeft dus de voorkeur aan de methode split() in plaats van de klasse StringTokenizer. We gebruiken de volgende twee methoden van de klasse:

StringTokenizer.hasMoreTokens()

De methode herhaalt de tekenreeks en controleert of er meer tokens beschikbaar zijn in de tokenizerreeks. Het retourneert waar als er één token beschikbaar is in de tekenreeks na de huidige positie, anders wordt onwaar geretourneerd. Het noemt intern de volgendeToken() methode als deze true retourneert en de methode nextToken() het token retourneert.

Syntaxis:

 public boolean hasMoreTokens() 

StringTokenizer.nextToken()

Het retourneert het volgende token uit de string-tokenizer. Het gooit NoSuchElementException als de tokens niet beschikbaar zijn in de stringtokenizer.

Syntaxis:

 public String nextToken() 

Laten we een programma maken dat de string splitst met behulp van de klasse 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()); } } } 

Uitgang:

booleaans in c
 Welcome to Javatpoint 

Met behulp van de Scanner.useDelimiter()-methode

Java Scanner klasse biedt de gebruikDelimiter() methode om de string in tokens te splitsen. Er zijn twee varianten van de methode useDelimiter():

  • useDelimiter(Patroonpatroon)
  • useDelimiter(tekenreekspatroon)

useDelimiter(Patroonpatroon)

De methode stelt het scheidingspatroon van de scanner in op de opgegeven tekenreeks. Het ontleedt een begrenzend patroon als een argument. Het retourneert de scanner.

Syntaxis:

 public Scanner useDelimiter(Pattern pattern) 

useDelimiter(tekenreekspatroon)

De methode stelt het scheidingspatroon van de scanner in op een patroon dat is opgebouwd uit de opgegeven tekenreeks. Het ontleedt een begrenzend patroon als een argument. Het retourneert de scanner.

Syntaxis:

 public Scanner useDelimiter(String pattern) 

Opmerking: beide bovenstaande methoden gedragen zich op dezelfde manier en roepen de useDelimiter(Pattern.compile(pattern)) aan.

In het volgende programma hebben we de methode useDelimiter() gebruikt om de tekenreeks te splitsen.

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

Uitgang:

 Do your work self