I Java, splitte streng er en viktig og vanligvis brukt operasjon ved koding. Java gir flere måter å splitte strengen . Men den vanligste måten er å bruke split() metode av String-klassen. I denne delen vil vi lære hvordan dele en streng i Java med skilletegn. Sammen med dette vil vi også lære noen andre metoder for å dele strengen, som bruken av StringTokenizer-klassen, Scanner.useDelimiter()-metoden . Før vi går over til emnet, la oss forstå hva er skilletegn.
Hva er en skilletegn?
I Java , skilletegn er tegnene som deler (separerer) strengen i tokens. Java lar oss definere alle tegn som skilletegn. Det er mange strengdelingsmetoder som tilbys av Java som bruker mellomromstegn som skilletegn. De mellomromsavgrensning er den standard skilletegn i Java.
Før vi går til programmet, la oss forstå konseptet med streng.
Strengen er bygd opp av to typer tekst som er tokens og skilletegn. Tokenene er ordene som er meningsfulle, og skilletegnene er tegnene som deler eller skiller symbolene. La oss forstå det gjennom et eksempel.
For å forstå skilletegn i Java , må vi være vennlige med Java regulært uttrykk . Det er nødvendig når skilletegnet brukes som et spesialtegn i regulære uttrykk, som (.) og (|).
Eksempel på skilletegn
streng: Javatpoint er det beste nettstedet for å lære nye teknologier.
I strengen ovenfor er tokens, Javatpoint, er, den, beste, nettsiden, for å, lære, nye, teknologier , og avgrensningene er mellomrom mellom de to symbolene.
Hvordan dele en streng i Java med skilletegn?
Java gir følgende måte å dele en streng i tokens:
Bruker Scanner.next()-metoden
Det er metoden til Scanner-klassen. Den finner og returnerer neste token fra skanneren. Den deler opp strengen i tokens med mellomromsavgrensning. Hele tokenet identifiseres av inngangen som samsvarer med skilletegnsmønsteret.
Syntaks:
public String next();
Det kaster NoSuchElementException hvis neste token ikke er tilgjengelig. Det kaster også IllegalStateException hvis inngangsskanneren er lukket.
La oss lage et program som deler et strengobjekt ved å bruke next()-metoden som bruker mellomrom til å dele strengen i tokens.
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(); } } }
Produksjon:
java gjør mens
Javatpoint is the best website to learn new technologies
I programmet ovenfor, et poeng å legge merke til at i konstruktøren av Scanner-klassen i stedet for å bestå System.in har vi sendt en strengvariabel str. Vi har gjort det fordi før vi manipulerer strengen, må vi lese strengen.
Bruker String.split()-metoden
De dele() metoden for String klasse brukes til å dele en streng i en rekke av strengobjekter basert på det angitte skilletegnet som samsvarer med det regulære uttrykket. Tenk for eksempel på følgende streng:
String str= 'Welcome,to,the,word,of,technology';
Strengen ovenfor er atskilt med komma. Vi kan dele opp strengen ovenfor ved å bruke følgende uttrykk:
String[] tokens=s.split(',');
Uttrykket ovenfor deler strengen inn i tokens når tokens skilles med et spesifisert skilletegn komma (,). Den angitte strengen delt inn i følgende strengobjekter:
Welcome to the word of technology
Det er to varianter av split()-metodene:
- delt (regex streng)
- delt (regex streng, int grense)
String.split(Regex streng)
Den deler strengen i henhold til spesifisert regulært uttrykk. Vi kan bruke en prikk (.), mellomrom ( ), komma (,) og et hvilket som helst tegn (som z, a, g, l osv.)
Syntaks:
public String[] split(String regex)
Metoden analyserer et regulært skilletegn som et argument. Den returnerer en rekke strengobjekter. Det kaster PatternSyntaxException hvis det analyserte regulære uttrykket har en ugyldig syntaks.
La oss bruke split()-metoden og dele strengen med komma.
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;>
I eksemplet ovenfor er strengobjektet avgrenset med komma. Split()-metoden deler opp strengen når den finner kommaet som skilletegn.
La oss se et annet eksempel der vi vil bruke flere skilletegn for å dele strengen.
innkapsling java
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(Regeks streng, int grense)
Det lar oss dele en streng spesifisert med skilletegn, men i et begrenset antall tokens. Metoden godtar to parametere regex (et avgrensende regulært uttrykk) og limit. Grenseparameteren brukes til å kontrollere antall ganger mønsteret brukes som påvirker den resulterende matrisen. Den returnerer en rekke String-objekter beregnet ved å dele den gitte strengen i henhold til grenseparameteren.
Det er en liten forskjell mellom varianten av split()-metodene at den begrenser antall tokens som returneres etter å ha påkalt metoden.
Syntaks:
public String[] split(String regex, int limit)
Det kaster PatternSyntaxException hvis det analyserte regulære uttrykket har en ugyldig syntaks.
Grenseparameteren kan være positiv, negativ eller lik grensen.
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;>
I kodebiten ovenfor ser vi at:
velg fra flere tabeller i sql
- Når grensen er 2, er antall tokens i strengmatrisen to.
- Når grensen er -3, deles den angitte strengen i 2 tokens. Det inkluderer de etterfølgende plassene.
- Når grensen er 0, deles den angitte strengen i 2 tokens. I dette tilfellet er etterfølgende plass utelatt.
Eksempel på Pipe Delimited String
Å dele en streng avgrenset med pipe (|) er litt vanskelig. Fordi pipen er et spesialtegn i Java regulære uttrykk.
La oss lage en streng avgrenset av rør og dele den for rør.
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;>
I eksemplet ovenfor ser vi at det ikke gir samme utgang som andre skilletegn gir. Det skal produsere en rekke tokens, livet ditt, og opprettelse , men det er det ikke. Det gir resultatet, som vi har sett i utgangen ovenfor.
Årsaken bak det at regulære uttrykksmotoren tolker røravgrenseren som en Logisk ELLER-operator . Regex-motoren deler strengen på tom streng.
For å løse dette problemet må vi flukt pipetegnet når det sendes til split()-metoden. Vi bruker følgende setning for å unnslippe pipe-karakteren:
String[] stringarray = s.split('\|');
Legg til et par omvendt skråstrek (\) før avgrenseren for å unnslippe røret. Etter å ha gjort endringene i programmet ovenfor, tolker regex-motoren pipetegnet som et skilletegn.
En annen måte å unnslippe pipetegnet er å sette pipetegnet innenfor et par firkantede parenteser, som vist nedenfor. I Java regex API fungerer paret med firkantede parenteser som en tegnklasse.
String[] stringarray = s.split('[|]');
Begge utsagnene ovenfor gir følgende utgang:
Produksjon:
Life is your creation
Bruker StringTokenizer Class
Java StringTokenizer er en eldre klasse som er definert i java.util-pakken. Det lar oss dele strengen i tokens. Den brukes ikke av programmereren fordi split()-metoden til String-klassen gjør det samme arbeidet. Så programmereren foretrekker split()-metoden i stedet for StringTokenizer-klassen. Vi bruker følgende to metoder i klassen:
StringTokenizer.hasMoreTokens()
Metoden itererer over strengen og sjekker om det er flere tokens tilgjengelig i tokenizer-strengen. Det returnerer sant hvis det er ett symbol som er tilgjengelig i strengen etter gjeldende posisjon, ellers returnerer den falsk. Den kaller internt nextToken() metoden hvis den returnerer true og nextToken()-metoden returnerer tokenet.
Syntaks:
public boolean hasMoreTokens()
StringTokenizer.nextToken()
Den returnerer neste token fra strengtokenizeren. Det kaster NoSuchElementException hvis tokenene ikke er tilgjengelige i strengtokenizeren.
Syntaks:
public String nextToken()
La oss lage et program som deler strengen ved å bruke StringTokenizer-klassen.
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()); } } }
Produksjon:
Welcome to Javatpoint
Bruke Scanner.useDelimiter()-metoden
Java Skanner klasse gir useDelimiter() metode for å dele strengen i tokens. Det er to varianter av useDelimiter()-metoden:
- useDelimiter(mønstermønster)
- useDelimiter(strengmønster)
useDelimiter(mønstermønster)
Metoden setter skannerens avgrensningsmønster til den angitte strengen. Den analyserer et avgrensende mønster som et argument. Den returnerer skanneren.
Syntaks:
public Scanner useDelimiter(Pattern pattern)
useDelimiter(strengmønster)
Metoden setter skannerens avgrensningsmønster til et mønster som konstrueres fra den angitte strengen. Den analyserer et avgrensende mønster som et argument. Den returnerer skanneren.
Syntaks:
public Scanner useDelimiter(String pattern)
Merk: Begge metodene ovenfor oppfører seg på samme måte, som påkaller useDelimiter(Pattern.compile(pattern)).
I det følgende programmet har vi brukt metoden useDelimiter() for å dele strengen.
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(); } }
Produksjon:
gjenta et kart i java
Do your work self