logo

Ako rozdeliť reťazec v Jave pomocou oddeľovača?

v Jave rozdeľovacia šnúra je dôležitá a zvyčajne používaná operácia pri kódovaní. Java ponúka viacero spôsobov rozdeľte reťazec . Najbežnejším spôsobom je však použitie metóda split(). triedy String. V tejto časti sa naučíme ako rozdeliť reťazec v Jave pomocou oddeľovača. Spolu s tým sa naučíme aj niektoré ďalšie metódy na rozdelenie reťazca, napríklad použitie triedy StringTokenizer, Metóda Scanner.useDelimiter(). . Skôr ako prejdeme k téme, poďme pochopiť čo je oddeľovač.

Čo je to oddeľovač?

In Java , oddeľovače sú znaky, ktoré rozdeľujú (oddeľujú) reťazec na tokeny. Java nám umožňuje definovať ľubovoľné znaky ako oddeľovač. Java ponúka mnoho metód delenia reťazcov, ktoré používajú ako oddeľovač medzery. The oddeľovač medzery je predvolený oddeľovač v Jave.

Skôr než prejdeme k programu, pochopme pojem reťazec.

Reťazec sa skladá z dvoch typov textu, ktoré sú žetóny a oddeľovače. Tokeny sú slová, ktoré majú zmysel, a oddeľovače sú znaky, ktoré rozdeľujú alebo oddeľujú tokeny. Poďme to pochopiť na príklade.

Aby ste pochopili oddeľovač v jazyku Java , musíme sa spriateliť s regulárny výraz Java . Je potrebné, keď sa oddeľovač používa ako špeciálny znak v regulárnych výrazoch, ako (.) a (|).

Príklad oddeľovača

Reťazec: Javatpoint je najlepšia webová stránka na učenie sa nových technológií.

Vo vyššie uvedenom reťazci sú tokeny, Javatpoint, je, najlepší, web, učiť sa, nové, technológie a oddeľovače sú medzery medzi dvoma tokenmi.

Ako rozdeliť reťazec v Jave pomocou oddeľovača?

Java poskytuje nasledujúci spôsob, ako rozdeliť reťazec na tokeny:

Pomocou metódy Scanner.next().

Je to metóda triedy Scanner. Nájde a vráti ďalší token zo skenera. Rozdelí reťazec na tokeny pomocou oddeľovača medzier. Úplný token je identifikovaný podľa vstupu, ktorý zodpovedá vzoru oddeľovača.

Syntax:

 public String next(); 

To hádže NoSuchElementException ak nasledujúci token nie je k dispozícii. Tiež hádže IllegalStateException ak je vstupný skener zatvorený.

Vytvorme program, ktorý rozdelí objekt typu reťazec pomocou metódy next(), ktorá používa medzery na rozdelenie reťazca na tokeny.

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

Výkon:

večera vs večera
 Javatpoint is the best website to learn new technologies 

Vo vyššie uvedenom programe si treba všimnúť, že v konštruktore triedy Scanner namiesto odovzdania System.in sme odovzdali reťazcovú premennú str. Urobili sme tak, pretože pred manipuláciou s reťazcom musíme reťazec prečítať.

Použitie metódy String.split().

The rozdeliť () metóda Reťazec trieda sa používa na rozdelenie reťazca do poľa objektov String na základe zadaného oddeľovača, ktorý sa zhoduje s regulárnym výrazom. Zvážte napríklad nasledujúci reťazec:

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

Vyššie uvedený reťazec je oddelený čiarkami. Vyššie uvedený reťazec môžeme rozdeliť pomocou nasledujúceho výrazu:

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

Vyššie uvedený výraz rozdeľuje reťazec na tokeny, keď sú tokeny oddelené špecifikovaným oddeľovacím znakom čiarkou (,). Zadaný reťazec sa rozdelí na nasledujúce reťazcové objekty:

 Welcome to the word of technology 

Existujú dva varianty metód split():

  • rozdeliť (regulárny výraz reťazca)
  • split (regulárny výraz reťazca, limit int)

String.split(regulárny výraz reťazca)

Rozdeľuje reťazec podľa zadaného regulárneho výrazu regulárneho výrazu. Môžeme použiť bodku (.), medzeru ( ), čiarku (,) a ľubovoľný znak (napríklad z, a, g, l atď.)

Syntax:

 public String[] split(String regex) 

Metóda analyzuje regulárny výraz oddeľovača ako argument. Vracia pole objektov typu String. To hádže PatternSyntaxException ak má analyzovaný regulárny výraz neplatnú syntax.

Použime metódu split() a rozdeľme reťazec čiarkou.

SplitStringExample2.java

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

Vo vyššie uvedenom príklade je objekt typu string oddelený čiarkou. Metóda split() rozdelí reťazec, keď nájde čiarku ako oddeľovač.

Pozrime sa na ďalší príklad, v ktorom použijeme viacero oddeľovačov na rozdelenie reťazca.

vyhľadávacie algoritmy

SplitStringExample3.java

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

String.split(regulárny výraz reťazca, limit int)

Umožňuje nám rozdeliť reťazec určený oddeľovačom, ale na obmedzený počet tokenov. Metóda akceptuje dva parametre regex (vymedzujúci regulárny výraz) a limit. Parameter limit sa používa na kontrolu počtu, koľkokrát sa použije vzor, ​​ktorý ovplyvňuje výsledné pole. Vracia pole objektov String vypočítané rozdelením daného reťazca podľa parametra limit.

Medzi variantom metód split() je malý rozdiel v tom, že obmedzuje počet tokenov vrátených po vyvolaní metódy.

Syntax:

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

To hádže PatternSyntaxException ak má analyzovaný regulárny výraz neplatnú syntax.

Parameter limitu môže byť kladný, záporný alebo rovný limitu.

SplitStringExample4.java

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

Vo vyššie uvedenom útržku kódu vidíme, že:

nahradiť reťazec v jazyku Java
  • Keď je limit 2, počet tokenov v poli reťazcov je dva.
  • Keď je limit -3, zadaný reťazec sa rozdelí na 2 tokeny. Zahŕňa medzery na konci.
  • Keď je limit 0, zadaný reťazec sa rozdelí na 2 tokeny. V tomto prípade je medzera na konci vynechaná.

Príklad reťazca oddeleného potrubím

Rozdelenie reťazca ohraničeného čiarou (|) je trochu zložité. Pretože potrubie je špeciálny znak v regulárnom výraze Java.

Vytvorme reťazec ohraničený fajkou a rozdeľme ho fajkou.

SplitStringExample5.java

 public class SplitStringExample5 { public static void main(String args[]) { //defining a String object String s = &apos;Life|is|your|creation&apos;; //split string delimited by comma String[] stringarray = s.split(&apos;|&apos;); //we can use dot, whitespace, any character //iterate over string array for(int i=0; i<stringarray.length; i++) { prints the tokens system.out.println(stringarray[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> L i f e | i s | y o u r | c r e a t i o n </pre> <p>In the above example, we see that it does not produce the same output as other delimiter yields. It should produce an array of tokens, <strong>life, yours,</strong> and <strong>creation</strong> , but it is not. It gives the result, as we have seen in the output above.</p> <p>The reason behind it that the regular expression engine interprets the pipe delimiter as a <strong>Logical OR operator</strong> . The regex engine splits the String on empty String.</p> <p>In order to resolve this problem, we must <strong>escape</strong> the pipe character when passed to the split() method. We use the following statement to escape the pipe character:</p> <pre> String[] stringarray = s.split(&apos;\|&apos;); </pre> <p>Add a pair of <strong>backslash (\)</strong> before the delimiter to escape the pipe. After doing the changes in the above program, the regex engine interprets the pipe character as a delimiter.</p> <p>Another way to escape the pipe character is to put the pipe character inside a pair of square brackets, as shown below. In the Java regex API, the pair of square brackets act as a character class.</p> <pre> String[] stringarray = s.split(&apos;[|]&apos;); </pre> <p>Both the above statements yield the following output:</p> <p> <strong>Output:</strong> </p> <pre> Life is your creation </pre> <h3>Using StringTokenizer Class</h3> <p>Java <strong>StringTokenizer</strong> is a legacy class that is defined in java.util package. It allows us to split the string into tokens. It is not used by the programmer because the split() method of the String class does the same work. So, the programmer prefers the split() method instead of the StringTokenizer class. We use the following two methods of the class:</p> <p> <strong>StringTokenizer.hasMoreTokens()</strong> </p> <p>The method iterates over the string and checks if there are more tokens available in the tokenizer string. It returns true if there is one token is available in the string after the current position, else returns false. It internally calls the <strong>nextToken()</strong> method if it returns true and the nextToken() method returns the token.</p> <p> <strong>Syntax:</strong> </p> <pre> public boolean hasMoreTokens() </pre> <p> <strong>StringTokenizer.nextToken()</strong> </p> <p>It returns the next token from the string tokenizer. It throws <strong>NoSuchElementException</strong> if the tokens are not available in the string tokenizer.</p> <p> <strong>Syntax:</strong> </p> <pre> public String nextToken() </pre> <p>Let&apos;s create a program that splits the string using the StringTokenizer class.</p> <p> <strong>SplitStringExample6.java</strong> </p> <pre> import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = &apos;Welcome/to/Javatpoint&apos;; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, &apos;/&apos;); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Welcome to Javatpoint </pre> <h2>Using Scanner.useDelimiter() Method</h2> <p>Java <strong>Scanner</strong> class provides the <strong>useDelimiter()</strong> method to split the string into tokens. There are two variants of the useDelimiter() method:</p> <ul> <li>useDelimiter(Pattern pattern)</li> <li>useDelimiter(String pattern)</li> </ul> <h3>useDelimiter(Pattern pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(Pattern pattern) </pre> <h3>useDelimiter(String pattern)</h3> <p>The method sets the scanner&apos;s delimiting pattern to a pattern that constructs from the specified string. It parses a delimiting pattern as an argument. It returns the Scanner.</p> <p> <strong>Syntax:</strong> </p> <pre> public Scanner useDelimiter(String pattern) </pre> <h4>Note: Both the above methods behave in the same way, as invoke the useDelimiter(Pattern.compile(pattern)).</h4> <p>In the following program, we have used the useDelimiter() method to split the string.</p> <p> <strong>SplitStringExample7.java</strong> </p> <pre> import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner(&apos;Do/your/work/self&apos;); //Initialize the string delimiter scan.useDelimiter(&apos;/&apos;); //checks if the tokenized Strings has next token while(scan.hasNext()) { //prints the next token System.out.println(scan.next()); } //closing the scanner scan.close(); } } </pre> <p> <strong>Output:</strong> </p> <pre> Do your work self </pre> <hr></stringarray.length;>

Vo vyššie uvedenom príklade vidíme, že neprodukuje rovnaký výstup ako výnosy iných oddeľovačov. Mal by produkovať pole tokenov, život, tvoj, a tvorba , ale nie je. Poskytuje výsledok, ako sme videli vo výstupe vyššie.

Dôvodom je, že motor regulárneho výrazu interpretuje oddeľovač zvislej čiary ako a Logický operátor OR . Regulátor regulárneho výrazu rozdeľuje reťazec na prázdny reťazec.

Aby sme tento problém vyriešili, musíme uniknúť znak potrubia pri odovzdaní metóde split(). Na opustenie znaku zvislej čiary používame nasledujúci príkaz:

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

Pridajte pár spätná lomka (\) pred oddeľovač, aby unikol z potrubia. Po vykonaní zmien vo vyššie uvedenom programe regex engine interpretuje znak zvislej čiary ako oddeľovač.

Ďalším spôsobom, ako uniknúť znaku zvislej čiary, je vložiť znak zvislej čiary do páru hranatých zátvoriek, ako je znázornené nižšie. V Java regex API funguje pár hranatých zátvoriek ako trieda znakov.

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

Obe vyššie uvedené vyhlásenia poskytujú nasledujúci výstup:

Výkon:

 Life is your creation 

Použitie triedy StringTokenizer

Java StringTokenizer je staršia trieda, ktorá je definovaná v balíku java.util. Umožňuje nám rozdeliť reťazec na žetóny. Programátor ju nepoužíva, pretože metóda split() triedy String robí rovnakú prácu. Programátor teda uprednostňuje metódu split() namiesto triedy StringTokenizer. Používame nasledujúce dve metódy triedy:

StringTokenizer.hasMoreTokens()

Metóda iteruje cez reťazec a kontroluje, či je v reťazci tokenizer k dispozícii viac tokenov. Ak je v reťazci za aktuálnou pozíciou k dispozícii jeden token, vráti hodnotu true, inak vráti hodnotu false. Vnútorne volá nextToken() metóda, ak vráti hodnotu true a metóda nextToken() vráti token.

Syntax:

 public boolean hasMoreTokens() 

StringTokenizer.nextToken()

Vráti ďalší token z reťazcového tokenizéra. To hádže NoSuchElementException ak tokeny nie sú dostupné v reťazcovom tokenizéri.

Syntax:

 public String nextToken() 

Vytvorme program, ktorý rozdelí reťazec pomocou triedy StringTokenizer.

SplitStringExample6.java

 import java.util.StringTokenizer; public class SplitStringExample6 { public static void main(String[] args) { //defining a String object String str = &apos;Welcome/to/Javatpoint&apos;; //constructor of the StringTokenizer class StringTokenizer tokens = new StringTokenizer(str, &apos;/&apos;); //checks if the string has more tokens or not while (tokens.hasMoreTokens()) { //prints the tokens System.out.println(tokens.nextToken()); } } } 

Výkon:

 Welcome to Javatpoint 

Použitie metódy Scanner.useDelimiter().

Java Skener trieda poskytuje useDelimiter() metóda na rozdelenie reťazca na tokeny. Existujú dva varianty metódy useDelimiter():

  • useDelimiter (vzor vzoru)
  • useDelimiter (vzor reťazca)

useDelimiter (vzor vzoru)

Metóda nastaví vymedzovací vzor skenera na zadaný reťazec. Ako argument analyzuje vymedzovací vzor. Vráti skener.

Syntax:

 public Scanner useDelimiter(Pattern pattern) 

useDelimiter (vzor reťazca)

Metóda nastaví vymedzovací vzor skenera na vzor, ​​ktorý sa vytvorí zo zadaného reťazca. Ako argument analyzuje vymedzovací vzor. Vráti skener.

Syntax:

 public Scanner useDelimiter(String pattern) 

Poznámka: Obe vyššie uvedené metódy sa správajú rovnakým spôsobom, pretože vyvolajte useDelimiter(Pattern.compile(pattern)).

V nasledujúcom programe sme na rozdelenie reťazca použili metódu useDelimiter().

SplitStringExample7.java

 import java.util.Scanner; public class SplitStringExample7 { public static void main(String args[]) { //construtor of the Scanner class Scanner scan = new Scanner(&apos;Do/your/work/self&apos;); //Initialize the string delimiter scan.useDelimiter(&apos;/&apos;); //checks if the tokenized Strings has next token while(scan.hasNext()) { //prints the next token System.out.println(scan.next()); } //closing the scanner scan.close(); } } 

Výkon:

linux ako premenovať adresár
 Do your work self