Java programoje skaidanti styga yra svarbi ir dažniausiai naudojama operacija koduojant. Java siūlo kelis būdus suskaldyti eilutę . Tačiau labiausiai paplitęs būdas yra naudoti split() metodas styginių klasės. Šiame skyriuje mes išmoksime kaip padalinti eilutę Java su skyrikliu. Be to, mes taip pat išmoksime keletą kitų metodų, kaip padalinti eilutę, pvz., StringTokenenizer klasės naudojimą, Scanner.useDelimiter() metodas . Prieš pereinant prie temos, supraskime kas yra skyriklis.
Kas yra skyriklis?
Į Java , skiriamieji ženklai yra simboliai, kurie suskaido (atskiria) eilutę į žetonus. Java leidžia mums apibrėžti bet kokius simbolius kaip skyriklį. Java siūlo daugybę eilučių padalijimo metodų, kurie kaip skirtuką naudoja tarpo simbolį. The tarpų skyriklis yra numatytasis skyriklis Java kalboje.
Prieš pereidami prie programos, supraskime eilutės sąvoką.
Eilutę sudaro dviejų tipų tekstai žetonų ir skiriamieji ženklai. Ženklai yra žodžiai, kurie turi prasmę, o skyrikliai yra simboliai, skiriantys arba atskiriantys žetonus. Supraskime tai per pavyzdį.
Norėdami suprasti skyriklis Java , mes turime draugauti su Java reguliarioji išraiška . Tai būtina, kai skyriklis naudojamas kaip specialus simbolis reguliariosiose išraiškose, pvz., (.) ir (|).
Skirstytuvo pavyzdys
Eilutė: Javatpoint yra geriausia svetainė mokytis naujų technologijų.
Aukščiau pateiktoje eilutėje žetonai yra Javapoint yra geriausia svetainė, skirta mokytis naujų technologijų , o skyrikliai yra tarpai tarp dviejų žetonų.
Kaip padalinti eilutę Java naudojant skyriklį?
„Java“ suteikia tokį būdą, kaip padalyti eilutę į žetonus:
Naudojant Scanner.next() metodą
Tai yra skaitytuvo klasės metodas. Jis suranda ir grąžina kitą žetoną iš skaitytuvo. Jis padalija eilutę į žetonus naudodamas tarpo skyriklį. Visas prieigos raktas identifikuojamas pagal įvestį, atitinkančią skiriamojo ženklo šabloną.
Sintaksė:
public String next();
Tai meta NoSuchElementException jei kito žetono nėra. Taip pat meta IllegalStateException jei įvesties skaitytuvas uždarytas.
Sukurkime programą, kuri skaido eilutės objektą naudojant next() metodą, kuris naudoja tarpą, kad padalytų eilutę į žetonus.
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(); } } }
Išvestis:
java eilučių kūrėjas
Javatpoint is the best website to learn new technologies
Aukščiau pateiktoje programoje atkreipkite dėmesį, kad skaitytuvo klasės konstruktoriuje, užuot perdavęs System.in, perdavėme eilutės kintamąjį str. Taip padarėme, nes prieš manipuliuodami eilute turime ją perskaityti.
Naudojant String.split() metodą
The padalinti () metodas Styga klasė naudojamas padalyti eilutę į eilučių objektų masyvą pagal nurodytą skyriklį, atitinkantį reguliariąją išraišką. Pavyzdžiui, apsvarstykite šią eilutę:
String str= 'Welcome,to,the,word,of,technology';
Aukščiau pateikta eilutė atskiriama kableliais. Aukščiau pateiktą eilutę galime padalinti naudodami šią išraišką:
String[] tokens=s.split(',');
Aukščiau pateikta išraiška padalija eilutę į žetonus, kai žetonai atskiriami nurodytu skiriamojo simbolio kableliu (,). Nurodyta eilutė suskaidyta į šiuos eilutės objektus:
Welcome to the word of technology
Yra du split() metodo variantai:
- padalijimas (eilutės reguliarusis reiškinys)
- padalijimas (eilutės reguliarusis reiškinys, tarpinis limitas)
String.split (Eilutės reguliarusis reiškinys)
Jis suskaido eilutę pagal nurodytą reguliariąją išraišką. Galime naudoti tašką (.), tarpą ( ), kablelį (,) ir bet kurį simbolį (pvz., z, a, g, l ir kt.)
Sintaksė:
public String[] split(String regex)
Metodas analizuoja skyriklio reguliariąją išraišką kaip argumentą. Jis grąžina eilučių objektų masyvą. Tai meta Šablono sintaksės išimtis jei išanalizuota reguliarioji išraiška turi neteisingą sintaksę.
Java konvencijų įvardijimas
Naudokime split() metodą ir eilutę padalinkime kableliu.
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;>
Aukščiau pateiktame pavyzdyje eilutės objektas yra atskirtas kableliu. Split() metodas suskaido eilutę, kai randa kablelį kaip skirtuką.
Pažiūrėkime kitą pavyzdį, kuriame eilutei padalinti naudosime kelis skyriklius.
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 (Eilutės reguliarusis reiškinys, tarpinis apribojimas)
Tai leidžia mums padalinti eilutę, nurodytą skyrikliu, bet į ribotą žetonų skaičių. Metodas priima du parametrus regex (ribojančią reguliariąją išraišką) ir limitą. Ribos parametras naudojamas kontroliuoti, kiek kartų taikomas šablonas, turintis įtakos gaunamam masyvui. Jis grąžina eilutės objektų masyvą, apskaičiuotą suskaidžius nurodytą eilutę pagal ribinį parametrą.
Yra nedidelis skirtumas tarp split() metodo varianto, nes jis riboja žetonų, grąžinamų iškvietus metodą, skaičių.
Sintaksė:
public String[] split(String regex, int limit)
Tai meta Šablono sintaksės išimtis jei išanalizuota reguliarioji išraiška turi neteisingą sintaksę.
Ribinis parametras gali būti teigiamas, neigiamas arba lygus ribai.
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;>
Aukščiau pateiktame kodo fragmente matome, kad:
- Kai riba yra 2, žetonų skaičius eilučių masyve yra du.
- Kai riba yra -3, nurodyta eilutė padalijama į 2 žetonus. Tai apima galines erdves.
- Kai riba yra 0, nurodyta eilutė padalijama į 2 žetonus. Šiuo atveju tarpas užpakalyje praleidžiamas.
Vamzdžiu atskirtos stygos pavyzdys
Brūkšniu (|) ribotą eilutę padalinti yra šiek tiek sudėtinga. Kadangi vamzdis yra specialus „Java“ reguliariosios išraiškos simbolis.
Sukurkime eilutę, ribojamą vamzdžiu, ir padalinkime ją vamzdžiu.
režisierius Karanas Joharas
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;>
Aukščiau pateiktame pavyzdyje matome, kad jis negamina tokios pačios produkcijos kaip ir kiti skiriamieji ženklai. Ji turėtų sukurti žetonų masyvą, gyvenimas, tavo, ir kūryba , bet taip nėra. Tai duoda rezultatą, kaip matėme aukščiau pateiktoje išvestyje.
Priežastis, dėl kurios reguliariosios išraiškos variklis interpretuoja vamzdžio skyriklį kaip a Loginis ARBA operatorius . Regex variklis padalija eilutę į tuščią eilutę.
Norėdami išspręsti šią problemą, turime Pabegti vamzdžio simbolis perduodamas split() metodui. Norėdami išvengti vamzdžio simbolio, naudojame šį teiginį:
String[] stringarray = s.split('\|');
Pridėkite porą pasvirasis brūkšnys (\) prieš skyriklį, kad ištrūktų iš vamzdžio. Atlikęs pirmiau pateiktos programos pakeitimus, reguliariosios reikšmės variklis interpretuoja vamzdžio simbolį kaip skirtuką.
Kitas būdas išvengti vamzdžio simbolio yra įterpti vamzdžio simbolį į porą laužtinių skliaustų, kaip parodyta toliau. Java regex API laužtinių skliaustų pora veikia kaip simbolių klasė.
String[] stringarray = s.split('[|]');
Abu aukščiau pateikti teiginiai duoda tokią išvestį:
Išvestis:
Life is your creation
Naudojant StringTokenenizer klasę
Java StringTokenizatorius yra pasenusi klasė, apibrėžta java.util pakete. Tai leidžia mums padalinti eilutę į žetonus. Programuotojas jo nenaudoja, nes String klasės metodas split() atlieka tą patį darbą. Taigi, programuotojas teikia pirmenybę split() metodui, o ne StringTokenenizer klasei. Mes naudojame šiuos du klasės metodus:
StringTokenizer.hasMoreTokens()
Metodas kartojasi per eilutę ir patikrina, ar prieigos raktų eilutėje yra daugiau prieigos raktų. Jis grąžina teisingą, jei eilutėje po dabartinės padėties yra vienas prieigos raktas, kitu atveju grąžina false. Jis viduje vadina nextToken() metodas, jei jis grąžina true, o metodas nextToken() grąžina prieigos raktą.
Sintaksė:
public boolean hasMoreTokens()
StringTokenenizer.nextToken()
Jis grąžina kitą žetoną iš eilutės žetonų. Tai meta NoSuchElementException jei žetonų nėra eilutės žetonų įrenginyje.
Sintaksė:
public String nextToken()
Sukurkime programą, kuri suskaido eilutę naudodami StringTokenenizer klasę.
įterpimo python
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()); } } }
Išvestis:
Welcome to Javatpoint
Naudojant Scanner.useDelimiter() metodą
Java Skaitytuvas klasė suteikia UseDelimiter() būdas padalyti eilutę į žetonus. Yra du UseDelimiter() metodo variantai:
- UseDelimiter (Šablonas)
- UseDelimiter (Eilutės šablonas)
UseDelimiter (Šablonas)
Metodas nustato skaitytuvo skiriamąjį šabloną į nurodytą eilutę. Jis analizuoja ribojantį modelį kaip argumentą. Jis grąžina skaitytuvą.
Sintaksė:
public Scanner useDelimiter(Pattern pattern)
UseDelimiter (Eilutės šablonas)
Metodas nustato skaitytuvo skiriamąjį raštą į šabloną, kuris sukuriamas iš nurodytos eilutės. Jis analizuoja ribojantį modelį kaip argumentą. Jis grąžina skaitytuvą.
Sintaksė:
public Scanner useDelimiter(String pattern)
Pastaba: abu aukščiau pateikti metodai veikia taip pat, kaip ir iškviečiamas useDelimiter(Pattern.compile(pattern)).
Šioje programoje naudojome useDelimiter() metodą, kad padalintume eilutę.
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(); } }
Išvestis:
Do your work self