1. split(regex,limit)
The first is the split method with two parameters:
Function:
Will separate the strings of the given regular expression (regex)
The first parameter is the separated character type passed in Symbol , such as "," etc. (can be any string)
The second parameter is passed in the integer limit, which represents this string Split into n parts (n here is limit).
Return value:
The array returned by this method Contains each substring of this string. These substrings end with the matched regular expression (that is, the first parameter regex entered), or by the string's Ending as an end.
Note:
The substrings in the array are arranged in the order in which they appear in this string.
If the input regex does not match any characters in the string, then the result array will have only one element, which is this string. (That is, if the input regex parameter does not appear in the string)
If there is a positive match at the beginning of the string (that is, there are >0 regex separations at the beginning of the string) symbol), then an empty leading substring will be included at the beginning of the result array.
public class test { public static void main(String[] args) { String str = ",,1,2,3,4"; // 注意这里字符串开头就匹配到了逗号 String[] s = str.split(",",10);// 这里先取10,后文介绍第二个参数 for (String string : s) { System.out.println("子字符串"+string); } System.out.println(s.length); } }
Running result:
There will be a before the first comma Empty substring
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array . (The meaning here is that the value of limit controls the length of the result array)
The above interpretation is as follows: (1) If the limit input is a positive number , then this pattern will apply limit - 1 times at most (that is, the input regex will only be used to match limit - 1 times in the string), the length of the array will not be greater than limit, and the last entry of the array will contain All inputs except the last matching delimiter (that is to say, the separated pattern is from the front to the back). Give a code for everyone to understand:
public class test { public static void main(String[] args) { String str = "1,2,3,4"; String[] s = str.split(",",2);//这里输入limit为2,即分成2部分 for (String string : s) { System.out.println("子字符串"+string); } System.out.println(s.length); } }
Running result:
characters The string is separated into 2 substrings, and the separation pattern is
from front to back (2) If the input limit is zero, the pattern will Applied as many times as possible, the resulting array can have any length, and the empty string at the end will be discarded . (That is, all regex delimiters in the string are matched), and the empty string is discarded , the code is as follows:
public class test { public static void main(String[] args) { String str = "1,2,3,4,,,";// 这里后面逗号之间的空字符串将被丢弃 String[] s = str.split(",",0); for (String string : s) { System.out.println("子字符串"+string); } System.out.println(s.length); } }
Running results:
The empty string at the end will not appear in the result array
(3 ) If the value of input limit is negative , the pattern will be applied as many times as possible, and the array can be of any length. (The empty string at the end will not be lost)
public class test { public static void main(String[] args) { String str = ",1,2,3,4,"; String[] s = str.split(",",-1);//limit值为负数 for (String string : s) { System.out.println("子字符串"+string); } System.out.println(s.length); } }
Running result:
The empty string at the end of the string will not be lost
2. split(regex)
The next split method with only one parameter is easy, that isThe default limit value is 0.
The working principle of this method is to call the two-parameter split method with the given regex parameter and a limit parameter that defaults to 0. Therefore, the trailing empty string is not included in the resulting array.
The above is the detailed content of How to use String.split() in Java. For more information, please follow other related articles on the PHP Chinese website!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
