在Java中,split()方法用于分隔字符串,可以根據(jù)匹配給定的正則表達(dá)式來拆分字符串。split()方法可以將一個字符串分割為子字符串,然后將結(jié)果作為字符串?dāng)?shù)組返回;語法“stringObj.split([regex,[limit]])”,參數(shù)regex指定正則表達(dá)式分隔符,limit指定分割的份數(shù)。
本教程操作環(huán)境:windows7系統(tǒng)、java8、Dell G3電腦。
java split()方法介紹
Java中的split()主要用于分隔字符串,可以根據(jù)匹配給定的正則表達(dá)式來拆分字符串。
split方法可以將一個字符串分割為子字符串,然后將結(jié)果作為字符串?dāng)?shù)組返回。
stringObj.split([regex,[limit]])
stringObj:必選項(xiàng)。要被分解的 String 對象或文字。該對象不會被 split 方法修改。
regex:可選項(xiàng)。字符串或 正則表達(dá)式 對象,它標(biāo)識了分隔字符串時使用的是一個還是多個字符。如果忽略該選項(xiàng),返回包含整個字符串的單一元素?cái)?shù)組。
limit:可選項(xiàng)。該值用來限制返回?cái)?shù)組中的元素個數(shù)。
說明:
split 方法的結(jié)果是一個字符串?dāng)?shù)組,在 stingObj 中每個出現(xiàn) separator 的位置都要進(jìn)行分解。separator 不作為任何數(shù)組元素的部分返回。
舉例:
public class SplitDemo { public static String[] ss = new String[20]; public SplitDemo() { String s = "The rain in Spain falls mainly in the plain."; // 在每個空格字符處進(jìn)行分解。 ss = s.split(" "); } public static void main(String[] args) { SplitDemo demo = new SplitDemo(); for (int i = 0; i < ss.length; i++) System.out.println(ss[i]); } }
程序結(jié)果:
The rain in Spain falls mainly in the plain.
split()方法的使用
分隔符可以是任意字符、符號、數(shù)字、字符串等。
1、split(String regex)
1.1 單個分隔符
public class Test { public static void main(String[] args) { String str="2018,text,今天"; //單個分隔符用引號括起來即可 String[] data = str.split(","); for(int i=0;i< data.length;i++){ System.out.println(data[i]); } } }
上述代碼輸出結(jié)果
如果分隔符本身就是"|",那么就需要使用轉(zhuǎn)義字符"\"讓其產(chǎn)生效果,否則結(jié)果相反。
public class Test { public static void main(String[] args) { String str="a|bc|8"; //java中\(zhòng)\表示一個普通\,\+特殊字符表示字符本身 String[] data = str.split("\\|"); for(int i=0;i< data.length;i++){ System.out.println(data[i]); } } }
反之如果直接使用則會有相反效果, 輸出字符串中的單個字符。如下所示:
public class Test { public static void main(String[] args) { String str="a|bc|8"; //java中\(zhòng)\表示一個普通\,\+特殊字符表示字符本身 String[] data = str.split("|"); for(int i=0;i< data.length;i++){ System.out.println(data[i]); } } }
1.2 多個分隔符
public class Test { public static void main(String[] args) { String str="2021年11月18日;英語,數(shù)學(xué),語文;"; //多個分隔符用引號括起來,并且用“|”進(jìn)行分割 String[] data = str.split(",|;"); for(int i=0;i< data.length;i++){ System.out.println(data[i]); } } }
1.3 正則表達(dá)式表示分隔符
在正則表達(dá)式中"\d+"表示一個或多個數(shù)字,是用于從一堆數(shù)字字母以及其它字符組成的字符串中獲取非數(shù)字字符或字符串。
public class Test { public static void main(String[] args) { String str="2018年11月18日abcd85gg688"; //正則表達(dá)式中\(zhòng)d+表示一個或多個數(shù)字,java中\(zhòng)\表示一個普通\ String[] data = str.split("\\d+"); for(int i=0;i< data.length;i++){ System.out.println(data[i]); } } }
?上述代碼輸出結(jié)果
特殊情況
字符串開頭有分隔符:開頭產(chǎn)生一個空字符串,其余正常。
分隔符相互緊挨著:每兩個分隔符產(chǎn)生一個空字符串,若有三個分隔符則會有2各空字符,以此類推。
字符串最尾部有分割符:末尾產(chǎn)生一個空字符串,其余正常。
2、split(String regex, int limit)
如果 limit > 0,(從左到右)最多分割 n - 1 次,數(shù)組的長度將不會大于 n,結(jié)尾的空字符串不會丟棄。
如果 limit
如果 limit = 0,匹配到多少次就分割多少次,數(shù)組可以是任何長度,并且結(jié)尾空字符串將被丟棄。
也就是說,使用split方法時,如果只填一個正則表達(dá)式,結(jié)尾空字符串將被丟棄
總結(jié):
(1)split表達(dá)式,其實(shí)就是一個正則表達(dá)式。* ?^ | 等符號在正則表達(dá)式中屬于一種有特殊含義的字符,如果使用此種字符作為分隔符,必須使用轉(zhuǎn)義符即\\加以轉(zhuǎn)義。
(2)如果使用多個分隔符則需要借助 | 符號,如二所示,但需要轉(zhuǎn)義符的仍然要加上分隔符進(jìn)行處理
更多編程相關(guān)知識,請?jiān)L問:編程教學(xué)??!
The above is the detailed content of What is the use of java split() method?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Full screen layout can be achieved using Flexbox or Grid. The core is to make the minimum height of the page the viewport height (min-height:100vh); 2. Use flex:1 or grid-template-rows:auto1frauto to make the content area occupy the remaining space; 3. Set box-sizing:border-box to ensure that the margin does not exceed the container; 4. Optimize the mobile experience with responsive media query; this solution is compatible with good structure and is suitable for login pages, dashboards and other scenarios, and finally realizes a full screen page layout with vertical centering and full viewport.

Selecting the Java SpringBoot React technology stack can build stable and efficient full-stack web applications, suitable for small and medium-sized to large enterprise-level systems. 2. The backend uses SpringBoot to quickly build RESTfulAPI. The core components include SpringWeb, SpringDataJPA, SpringSecurity, Lombok and Swagger. The front-end separation is achieved through @RestController returning JSON data. 3. The front-end uses React (in conjunction with Vite or CreateReactApp) to develop a responsive interface, uses Axios to call the back-end API, and ReactRouter

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi
