前言
相信大家应该都知道在java编程中,有时候我们需要把一个字符串按照某个特定字符、字母等作为截点分割这个字符串,这样我们就可以使用这个字符串的一部分或者把所有截取的内容保存到数组里等操作。下面这篇文章就给大家分享了两种分割的方法,下面来一起看看吧。
一、java.lang.String 的 split() 方法, JDK 1.4 or later
public String[] split(String regex,int limit)
示例代码
public class StringSplit { public static void main(String[] args) { String sourceStr = "1,2,3,4,5"; String[] sourceStrArray = sourceStr.split(","); for (int i = 0; i < sourceStrArray.length; i++) { System.out.println(sourceStrArray[i]); } // 最多分割出3个字符串 int maxSplit = 3; sourceStrArray = sourceStr.split(",", maxSplit); for (int i = 0; i < sourceStrArray.length; i++) { System.out.println(sourceStrArray[i]); } } }
输出结果:
1 2 3 4 5 1 2 3,4,5
split 的实现直接调用的 matcher 类的 split 的方法。在使用String.split方法分隔字符串时,分隔符如果用到一些特殊字符,可能会得不到我们预期的结果。
在正则表达式中有特殊的含义的字符,我们使用的时候必须进行转义,示例:
public class StringSplit { public static void main(String[] args) { String value = "192.168.128.33"; // 注意要加\\,要不出不来,yeah String[] names = value.split("\\."); for (int i = 0; i < names.length; i++) { System.out.println(names[i]); } } }
split分隔符总结
1.字符"|","*","+"都得加上转义字符,前面加上"\\"。
2.而如果是"\",那么就得写成"\\\\"。
3.如果一个字符串中有多个分隔符,可以用"|"作为连字符。
比如:String str = "Java string-split#test",可以用Str.split(" |-|#")把每个字符串分开。这样就把字符串分成了3个子字符串。
二、java.util.Tokenizer JDK 1.0 or later
StringTokenizer
StringTokenizer 类允许应用程序将字符串分解为标记。StringTokenizer 是出于兼容性的原因而被保留的遗留类(虽然在新代码中并不鼓励使用它)。建议所有寻求此功能的人使用 String 的 split 方法或 java.util.regex 包。
代码示例
public class StringSplit { public static void main(String[] args) { String ip = "192.168.128.33"; StringTokenizer token=new StringTokenizer(ip,"."); while(token.hasMoreElements()){ System.out.print(token.nextToken()+" "); } } }
但是StringTokenizer对于字符串"192.168..33"的分割,返回的字符串数组只有3个元素,对于两个分隔符之间的空字符串会忽略,这个要慎重使用。
但是String.split(String.split是用正则表达式匹配,所以不使用KMP字符串匹配算法)用的都是按顺序遍历的算法,时间复杂度O(m*n),较高,所以性能上,StringTokenizer好很多,对于频繁使用字符串分割的应用,例如etl数据处理,使用StringTokenizer性能可以提高很多。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
更多Java中分割字符串的两种方法实例详解相关文章请关注PHP中文网!

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

To solve platform-specific problems in Java applications, you can take the following steps: 1. Use Java's System class to view system properties to understand the running environment. 2. Use the File class or java.nio.file package to process file paths. 3. Load the local library according to operating system conditions. 4. Use VisualVM or JProfiler to optimize cross-platform performance. 5. Ensure that the test environment is consistent with the production environment through Docker containerization. 6. Use GitHubActions to perform automated testing on multiple platforms. These methods help to effectively solve platform-specific problems in Java applications.

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
