Java valodā, šķeļ stīgu ir svarīga un parasti tiek izmantota kodēšanas operācija. Java nodrošina vairākus veidus, kā sadaliet virkni . Bet visizplatītākais veids ir izmantot split() metode no stīgu klases. Šajā sadaļā mēs uzzināsim kā sadalīt virkni Java ar atdalītāju. Līdztekus tam mēs apgūsim arī dažas citas metodes virknes sadalīšanai, piemēram, StringTokenizer klases izmantošanu, Scanner.useDelimiter() metode . Pirms pāriet pie tēmas, sapratīsim kas ir norobežotājs.
Kas ir norobežotājs?
In Java , norobežotāji ir rakstzīmes, kas sadala (atdala) virkni marķieros. Java ļauj mums definēt jebkuras rakstzīmes kā norobežotāju. Java piedāvā daudzas virkņu sadalīšanas metodes, kas kā atdalītāju izmanto atstarpes rakstzīmi. The atstarpes atdalītājs ir noklusējuma norobežotājs Java valodā.
Pirms pāriet uz programmu, sapratīsim virknes jēdzienu.
Virkne sastāv no divu veidu teksta, kas ir žetonus un norobežotāji. Marķieri ir nozīmīgi vārdi, un atdalītāji ir rakstzīmes, kas sadala vai atdala marķierus. Sapratīsim to, izmantojot piemēru.
Lai saprastu, norobežotājs Java valodā , mums ir jādraudzējas ar Java regulārā izteiksme . Tas ir nepieciešams, ja atdalītājs tiek izmantots kā īpaša rakstzīme regulārajās izteiksmēs, piemēram, (.) un (|).
Norobežotāja piemērs
Virkne: Javapoint ir labākā vietne jaunu tehnoloģiju apguvei.
Iepriekš minētajā virknē marķieri ir Javapoint ir labākā vietne, lai apgūtu jaunas tehnoloģijas , un norobežotāji ir atstarpes starp diviem žetoniem.
Kā sadalīt virkni Java, izmantojot atdalītāju?
Java nodrošina šādu veidu, kā sadalīt virkni marķieros:
- Izmantojot metodi Scanner.next()
- Izmantojot String.split() metodi
- StringTokenizer klases izmantošana
Izmantojot metodi Scanner.next()
Tā ir skeneru klases metode. Tas atrod un atgriež nākamo marķieri no skenera. Tas sadala virkni marķieros, izmantojot atstarpes atdalītāju. Pilns marķieris tiek identificēts pēc ievades, kas atbilst norobežotāja modelim.
Sintakse:
public String next();
Tas met NoSuchElementException ja nākamais marķieris nav pieejams. Tā arī met IllegalStateException ja ievades skeneris ir aizvērts.
Izveidosim programmu, kas sadala virknes objektu, izmantojot next() metodi, kas izmanto atstarpes, lai sadalītu virkni marķieros.
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(); } } }
Izvade:
apaļa matemātika java
Javatpoint is the best website to learn new technologies
Iepriekš minētajā programmā jāatzīmē, ka Scanner klases konstruktorā tā vietā, lai nodotu System.in, mēs esam nodevuši virknes mainīgo str. Mēs to darījām, jo pirms manipulācijas ar virkni mums ir jāizlasa virkne.
Izmantojot String.split() metodi
The sadalīt () metode Stīga klasē tiek izmantots, lai sadalītu virkni virknes objektu masīvā, pamatojoties uz norādīto atdalītāju, kas atbilst regulārajai izteiksmei. Piemēram, apsveriet šādu virkni:
String str= 'Welcome,to,the,word,of,technology';
Iepriekš minētā virkne ir atdalīta ar komatiem. Mēs varam sadalīt iepriekš minēto virkni, izmantojot šādu izteiksmi:
String[] tokens=s.split(',');
Iepriekš minētā izteiksme sadala virkni marķieros, kad marķieri ir atdalīti ar norādīto norobežojošo rakstzīmju komatu (,). Norādītā virkne tika sadalīta šādos virkņu objektos:
Welcome to the word of technology
Ir divi split() metodes varianti:
- sadalīt (virknes regex)
- sadalīt (virknes regulārais izteiksme, iekšējais ierobežojums)
String.split (virknes regex)
Tas sadala virkni saskaņā ar norādīto regulāro izteiksmi regex. Mēs varam izmantot punktu (.), atstarpi (), komatu (,) un jebkuru rakstzīmi (piemēram, z, a, g, l utt.)
Sintakse:
public String[] split(String regex)
Metode parsē norobežotāja regulāro izteiksmi kā argumentu. Tas atgriež virknes objektu masīvu. Tas met PatternSyntaxException ja parsētajai regulārajai izteiksmei ir nederīga sintakse.
Izmantosim split() metodi un sadalīsim virkni ar komatu.
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;>
Iepriekš minētajā piemērā virknes objekts ir norobežots ar komatu. Split() metode sadala virkni, kad tā atrod komatu kā atdalītāju.
Apskatīsim vēl vienu piemēru, kurā virknes sadalīšanai izmantosim vairākus atdalītājus.
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 (virknes regex, iekšējais ierobežojums)
burbuļu kārtošana algoritmā
Tas ļauj mums sadalīt virkni, kas norādīta ar norobežotāju, bet ierobežotā skaitā marķieru. Metode pieņem divus parametrus regex (ierobežojoša regulāra izteiksme) un limitu. Ierobežojuma parametrs tiek izmantots, lai kontrolētu, cik reižu tiek lietots modelis, kas ietekmē iegūto masīvu. Tas atgriež virknes objektu masīvu, kas aprēķināts, sadalot doto virkni atbilstoši ierobežojuma parametram.
Pastāv neliela atšķirība starp split() metožu variantu, jo tas ierobežo tokenu skaitu, kas tiek atgriezti pēc metodes izsaukšanas.
Sintakse:
public String[] split(String regex, int limit)
Tas met PatternSyntaxException ja parsētajai regulārajai izteiksmei ir nederīga sintakse.
Ierobežojuma parametrs var būt pozitīvs, negatīvs vai vienāds ar ierobežojumu.
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;>
Iepriekš minētajā koda fragmentā mēs redzam, ka:
- Ja ierobežojums ir 2, tokenu skaits virknes masīvā ir divi.
- Ja ierobežojums ir -3, norādītā virkne tiek sadalīta 2 marķieros. Tas ietver beigu atstarpes.
- Ja ierobežojums ir 0, norādītā virkne tiek sadalīta 2 marķieros. Šajā gadījumā beigu atstarpe tiek izlaista.
Caurules norobežotas virknes piemērs
Ar caurulīti (|) norobežotas virknes sadalīšana ir nedaudz sarežģīta. Tā kā caurule ir īpaša rakstzīme Java regulārajā izteiksmē.
Izveidosim virkni, ko norobežo caurule, un sadalīsim to ar cauruli.
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;>
Iepriekš minētajā piemērā redzams, ka tas nerada tādu pašu izvadi kā citi norobežotāji. Tam vajadzētu radīt žetonu masīvu, dzīve, tava, un radīšanu , bet tā nav. Tas dod rezultātu, kā mēs redzējām iepriekš sniegtajā izlaidē.
Iemesls tam, ka regulārās izteiksmes programma interpretē caurules norobežotāju kā a Loģiskais VAI operators . Regulārais dzinējs sadala virkni tukšā virknē.
Lai atrisinātu šo problēmu, mums ir bēgt caurules rakstzīme, kad tā tiek nodota split() metodei. Mēs izmantojam šādu paziņojumu, lai izvairītos no caurules rakstzīmes:
String[] stringarray = s.split('\|');
Pievienojiet pāris atpakaļvērstā slīpsvītra (\) pirms norobežotāja, lai izvairītos no caurules. Pēc izmaiņu veikšanas iepriekš minētajā programmā regex dzinējs interpretē caurules rakstzīmi kā norobežotāju.
Vēl viens veids, kā izvairīties no caurules rakstzīmes, ir ievietot caurules rakstzīmi kvadrātiekavās, kā parādīts tālāk. Java regex API kvadrātiekavu pāris darbojas kā rakstzīmju klase.
String[] stringarray = s.split('[|]');
Abi iepriekš minētie apgalvojumi dod šādu rezultātu:
Izvade:
Life is your creation
StringTokenizer klases izmantošana
Java StringTokenizer ir mantota klase, kas ir definēta pakotnē java.util. Tas ļauj mums sadalīt virkni marķieros. Programmētājs to neizmanto, jo String klases metode split () veic to pašu darbu. Tātad programmētājs dod priekšroku split() metodei, nevis klasei StringTokenenizer. Mēs izmantojam šādas divas klases metodes:
celtnieka dizaina modelis
StringTokenizer.hasMoreTokens()
Metode atkārto virkni un pārbauda, vai marķiera virknē ir pieejami vairāk marķieru. Tas atgriež patiesu, ja virknē pēc pašreizējās pozīcijas ir pieejams viens marķieris, pretējā gadījumā atgriež false. Tā iekšēji izsauc nextToken() metodi, ja tā atgriež true un nextToken() metode atgriež marķieri.
Sintakse:
public boolean hasMoreTokens()
StringTokenizer.nextToken()
Tas atgriež nākamo marķieri no virknes marķiera. Tas met NoSuchElementException ja marķieri nav pieejami virknes marķieri.
Sintakse:
public String nextToken()
Izveidosim programmu, kas sadala virkni, izmantojot StringTokenizer klasi.
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()); } } }
Izvade:
Welcome to Javatpoint
Izmantojot Scanner.useDelimiter() metodi
Java Skeneris klase nodrošina useDelimiter() metode, lai sadalītu virkni marķieros. Ir divi useDelimiter() metodes varianti:
Rendēt karti
- UseDelimiter (raksta raksts)
- useDelimiter (virknes raksts)
izmantot atdalītāju (raksta raksts)
Metode iestata skenera norobežojošo rakstu norādītajai virknei. Tas parsē norobežojošo modeli kā argumentu. Tas atgriež skeneri.
Sintakse:
public Scanner useDelimiter(Pattern pattern)
useDelimiter (virknes raksts)
Metode iestata skenera norobežojošo modeli uz modeli, kas tiek veidots no norādītās virknes. Tas parsē norobežojošo modeli kā argumentu. Tas atgriež skeneri.
Sintakse:
public Scanner useDelimiter(String pattern)
Piezīme. Abas iepriekš minētās metodes darbojas tāpat, kā izsauc useDelimiter(Pattern.compile(pattern)).
Nākamajā programmā mēs esam izmantojuši metodi useDelimiter (), lai sadalītu virkni.
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(); } }
Izvade:
Do your work self