Table of Contents
1. split(regex,limit)
2. split(regex)
Home Java javaTutorial How to use String.split() in Java

How to use String.split() in Java

Apr 18, 2023 pm 01:19 PM
java string.split()

1. split(regex,limit)

The first is the split method with two parameters:

How to use String.split() in Java

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:

  1. The substrings in the array are arranged in the order in which they appear in this string.

  2. 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)

  3. 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);
    }

}
Copy after login

Running result:

There will be a before the first comma Empty substring

How to use String.split() in Java

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)

How to use String.split() in Java

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

}
Copy after login

Running result:

characters The string is separated into 2 substrings, and the separation pattern is

How to use String.split() in Java

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

}
Copy after login

Running results:

The empty string at the end will not appear in the result array

How to use String.split() in Java

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

}
Copy after login

Running result:

The empty string at the end of the string will not be lost

How to use String.split() in Java

2. split(regex)

The next split method with only one parameter is easy, that isThe default limit value is 0.

How to use String.split() in Java

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.

How to use String.split() in Java

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles