Java中split主要用于分隔字符串,可以根據(jù)匹配給定的正則表達式來拆分字符串;語法格式“String.split(String regex, int limit)”,參數(shù)regex指定正則表達式分隔符,limit指定分割的份數(shù)。
相關(guān)推薦:《Java視頻教程》
split 方法
將一個字符串分割為子字符串,然后將結(jié)果作為字符串?dāng)?shù)組返回。
stringObj.split([regex,[limit]])
stringObj:必選項。要被分解的 String 對象或文字。該對象不會被 split 方法修改。
regex:可選項。字符串或 正則表達式 對象,它標(biāo)識了分隔字符串時使用的是一個還是多個字符。如果忽略該選項,返回包含整個字符串的單一元素數(shù)組。
limit:可選項。該值用來限制返回數(shù)組中的元素個數(shù)。
說明:
split 方法的結(jié)果是一個字符串?dāng)?shù)組,在 stingObj 中每個出現(xiàn) separator 的位置都要進行分解。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."; // 在每個空格字符處進行分解。 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.
public string[] split(string regex)
這里的參數(shù)的名稱是 regex ,也就是 regular expression (正則表達式)。這個參數(shù)并不是一個簡單的分割用的字符,而是一個正則表達式
public string[] split(string regex, int limit) { return pattern.compile(regex).split(this, limit); }
split 的實現(xiàn)直接調(diào)用的 matcher 類的 split 的方法。讀者已經(jīng)知道,“ . ”在正則表達式中有特殊的含義,因此我們使用的時候必須進行轉(zhuǎn)義。
只要將
String[] names = value.split(".");
改為
String[] names = value.split("//.");
就可以了。
在java.lang包中有String.split()方法,返回是一個數(shù)組
特殊情況有 * ^ : | . \
一、單個符號作為分隔符
- String address="上海\上海市|閔行區(qū)\吳中路";
String[] splitAddress=address.split("\\"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- String address="上海|上海市|閔行區(qū)|吳中路";
String[] splitAddress=address.split("\\|"); //如果以豎線為分隔符,則split的時候需要加上兩個斜杠【\\】進行轉(zhuǎn)義 System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- String address="上海*上海市*閔行區(qū)*吳中路";
String[] splitAddress=address.split("\\*"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- String address="上海:上海市:閔行區(qū):吳中路";
String[] splitAddress=address.split("\\:"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- String address="上海.上海市.閔行區(qū).吳中路";
String[] splitAddress=address.split("\\."); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- String address="上海^上海市^閔行區(qū)^吳中路";
String[] splitAddress=address.split("\\^"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- String address="上海@上海市@閔行區(qū)@吳中路";
String[] splitAddress=address.split("@"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
- String address="上海,上海市,閔行區(qū),吳中路";
String[] splitAddress=address.split(","); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
二、多個符號作為分隔符
String address="上海^上海市@閔行區(qū)#吳中路";
String[] splitAddress=address.split("\\^|@|#"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
例:
String address = new String("192.168.13.240"); String[] str = address.split("\\."); for(String s : str){ System.out.println(s); }
輸出格式:
192 168 13 240
總結(jié):(1)split表達式,其實就是一個正則表達式。* ?^ | 等符號在正則表達式中屬于一種有特殊含義的字符,如果使用此種字符作為分隔符,必須使用轉(zhuǎn)義符即\\加以轉(zhuǎn)義。
??????????(2)如果使用多個分隔符則需要借助 | 符號,如二所示,但需要轉(zhuǎn)義符的仍然要加上分隔符進行處理
更多編程相關(guān)知識,請訪問:編程教學(xué)??!
The above is the detailed content of How to use 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)

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.

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

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
