Java里String.split需要注意的用法

我們常常用String的split()方法去分割字符串,有兩個地方值得注意:

?

1. 當分隔符是句號時("."),需要轉義:

由于String.split是基于正則表達式來分割字符串,而句號在正則表達式里表示任意字符。

//Wrong:
//String[] words = tmp.split(".");//Correct:
String[] words = tmp.split("\\.");

所以,假設分隔符在正則表達式里有一定的意義時,需要格外留心,必須將它們轉義才能達到分割的效果。

?

2. 假設字符串最后有連續多個分隔符,且這些分隔符都需要被分割的話,需要調用split(String regex,int limit)這個方法:

String abc = "a,b,c,,,";
String[] str = abc.split(",");System.out.println(Arrays.toString(str)+" "+str.length);String[] str2 = abc.split(",",-1);System.out.println(Arrays.toString(str2)+" "+str2.length);

輸出如下:

[a, b, c] 3
[a, b, c, , , ] 6

需要輸出csv文件的時候,尤其需要注意。

?

3. 假設需要快速分割字符串,split()并不是最有效的方法。在split()方法內,有如下的實現:

1 public String[] split(String regex, int limit) {
2       return Pattern.compile(regex).split(this, limit);
3 }

頻繁調用split()會不斷創建Pattern這個對象,因此可以這樣去實現,減少Pattern的創建:

1 //create the Pattern object outside the loop    
2 Pattern pattern = Pattern.compile(" ");
3 
4 for (int i = 0; i < 1000000; i++)
5 {
6     String[] split = pattern.split("Hello World", 0);
7     list.add(split);
8 }

另外split()也往往比indexOf()+subString()這個組合分割字符串要稍慢,詳情可看這個帖子。

我在本機做過測試,感覺indexOf()+subString()比split()快一倍:

 1 public static void main(String[] args) {
 2         StringBuilder sb = new StringBuilder();
 3         for (int i = 100000; i < 100000 + 60; i++)
 4             sb.append(i).append(' ');
 5         String sample = sb.toString();
 6 
 7         int runs = 100000;
 8         for (int i = 0; i < 5; i++) {
 9             {
10                 long start = System.nanoTime();
11                 for (int r = 0; r < runs; r++) {
12                     StringTokenizer st = new StringTokenizer(sample);
13                     List<String> list = new ArrayList<String>();
14                     while (st.hasMoreTokens())
15                         list.add(st.nextToken());
16                 }
17                 long time = System.nanoTime() - start;
18                 System.out.printf("StringTokenizer took an average of %.1f us%n", time / runs
19                         / 1000.0);
20             }
21             {
22                 long start = System.nanoTime();
23                 Pattern spacePattern = Pattern.compile(" ");
24                 for (int r = 0; r < runs; r++) {
25                     List<String> list = Arrays.asList(spacePattern.split(sample, 0));
26                 }
27                 long time = System.nanoTime() - start;
28                 System.out.printf("Pattern.split took an average of %.1f us%n", time / runs
29                         / 1000.0);
30             }
31             {
32                 long start = System.nanoTime();
33                 for (int r = 0; r < runs; r++) {
34                     List<String> list = new ArrayList<String>();
35                     int pos = 0, end;
36                     while ((end = sample.indexOf(' ', pos)) >= 0) {
37                         list.add(sample.substring(pos, end));
38                         pos = end + 1;
39                     }
40                 }
41                 long time = System.nanoTime() - start;
42                 System.out
43                         .printf("indexOf loop took an average of %.1f us%n", time / runs / 1000.0);
44             }
45         }
46     }

在jdk1.7測試后,結果如下:

StringTokenizer took an average of 7.2 us
Pattern.split took an average of 7.9 us
indexOf loop took an average of 3.5 us

------------------------------------------
StringTokenizer took an average of 6.8 us
Pattern.split took an average of 5.4 us
indexOf loop took an average of 3.1 us

------------------------------------------
StringTokenizer took an average of 6.0 us
Pattern.split took an average of 5.5 us
indexOf loop took an average of 3.1 us

------------------------------------------
StringTokenizer took an average of 5.9 us
Pattern.split took an average of 5.5 us
indexOf loop took an average of 3.1 us

------------------------------------------
StringTokenizer took an average of 6.4 us
Pattern.split took an average of 5.5 us
indexOf loop took an average of 3.2 us

?

本文完

轉載于:https://www.cnblogs.com/techyc/p/3709182.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377052.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377052.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377052.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C# Socket 例子(控制臺程序)

服務器代碼 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO;namespace TCPListener {class Program{static void Main(string[] args){const int BufferSize 1024;Con…

Scala中的值類

Value classes are a special mechanism in Scala that is used to help the compiler to avoid allocating run time objects. 值類是Scala中的一種特殊機制&#xff0c;用于幫助編譯器避免分配運行時對象。 This is done by defining a subclass of AnyVal. The only parame…

《MySQL8.0.22:Lock(鎖)知識總結以及源碼分析》

目錄1、關于鎖的一些零碎知識&#xff0c;需要熟知事務加鎖方式&#xff1a;Innodb事務隔離MVCC多版本并發控制常用語句 與 鎖的關系意向鎖行級鎖2、鎖的內存結構以及一些解釋3、InnoDB的鎖代碼實現鎖系統結構lock_sys_tlock_t 、lock_rec_t 、lock_table_tbitmap鎖的基本模式的…

關于ORA-04021解決辦法(timeout occurred while waiting to lock object)

某個應用正在鎖定該表或者包 表為 select b.SID,b.SERIAL#,c.SQL_TEXT from v$locked_object a, v$session b, v$sqlarea c where a.SESSION_ID b.SID and b.SQL_ADDRESS c.ADDRESS and c.sql_text like %table_name% 包為 select B.SID,b.USERNAME,b.MACHINE FROM V$ACCESS …

HtmlAutoTestFrameWork

前段時間做的自動化測試的是Silverlight的&#xff0c;框架都已經搭好。突然測試發現這里還有一個要發送郵件的html頁面&#xff0c;并且將另外啟動瀏覽器&#xff0c;于是今天下午把這個html的也寫出來。用法 &#xff1a; HtmlAutoTestFrameWork htf new HtmlAutoTestFrameW…

L8ER的完整形式是什么?

L8ER&#xff1a;稍后 (L8ER: Later) L8ER is an abbreviation of "Later". L8ER是“ Later”的縮寫 。 It is an expression, which is commonly used in messaging or chatting on social media networking sites like Facebook, Yahoo Messenger, and Gmail, etc…

Randomize select algorithm 隨機選擇算法

從一個序列里面選擇第k大的數在沒有學習算法導論之前我想最通用的想法是給這個數組排序&#xff0c;然后按照排序結果返回第k大的數值。如果使用排序方法來做的話時間復雜度肯定至少為O&#xff08;nlgn&#xff09;。 問題是從序列中選擇第k大的數完全沒有必要來排序&#xff…

《Linux雜記:一》

目錄CPU負載和CPU利用率CPU負載很高,利用率卻很低的情況負載很低,利用率卻很高常用linux命令常用的文件、目錄命令常用的權限命令常用的壓縮命令CPU負載和CPU利用率 可以通過 uptime , w 或者 top 命令看到CPU的平均負載。 Load Average :負載的3個數字,比如上圖的0.57、0.4…

IOS Plist操作

代碼&#xff1a;copy BUNDLE下的plist文件 到 library下面。 bundle下不支持些&#xff0c;library&#xff0c;doc路徑支持讀與寫。 (void)copyUserpigListToLibrary {NSFileManager *fileManager [NSFileManager defaultManager];NSArray *paths NSSearchPathForDirector…

《線程管理:線程基本操作》

目錄線程管理啟動線程與&#xff08;不&#xff09;等待線程完成特殊情況下的等待&#xff08;使用trycath或rall&#xff09;后臺運行線程線程管理 啟動線程與&#xff08;不&#xff09;等待線程完成 提供的函數對象被復制到新的線程的存儲空間中&#xff0c;函數對象的執行…

scala特質_Scala的特質

scala特質Scala特質 (Scala traits) Traits in Scala are like interfaces in Java. A trait can have fields and methods as members, these members can be abstract and non-abstract while creation of trait. Scala中的特性類似于Java中的接口 。 特征可以具有作為成員的…

優化PHP代碼的40條建議(轉)

優化PHP代碼的40條建議 40 Tips for optimizing your php Code 原文地址&#xff1a;http://reinholdweber.com/?p3 英文版權歸Reinhold Weber所有&#xff0c;中譯文作者yangyang&#xff08;aka davidkoree&#xff09;。雙語版可用于非商業傳播&#xff0c;但須注明英文版作…

Iptables入門教程

轉自&#xff1a;http://drops.wooyun.org/tips/1424 linux的包過濾功能&#xff0c;即linux防火墻&#xff0c;它由netfilter 和 iptables 兩個組件組成。 netfilter 組件也稱為內核空間&#xff0c;是內核的一部分&#xff0c;由一些信息包過濾表組成&#xff0c;這些表包含內…

《線程管理:傳遞參數、確定線程數量、線程標識》

參考《c Concurrency In Action 》第二章做的筆記 目錄傳遞參數量產線程線程標識傳遞參數 thread構造函數的附加參數會拷貝至新線程的內存空間中&#xff0c;即使函數中的采納數是引用類型&#xff0c;拷貝操作也會執行。如果我們期待傳入一個引用&#xff0c;必須使用std::re…

手把手玩轉win8開發系列課程(14)

這節的議程就是——添加appbar appbar是出現在哪兒了&#xff0c;出現在屏幕的底部。他能使用戶能用手勢或者使用鼠標操作程序。metro UI 重點是在主要的控件使用許多控件&#xff0c;使其用戶使用win8電腦更加的方便。而appBar使其用戶體驗更好。在這節中&#xff0c;我將告訴…

No identities are available for signing 的解決辦法

今天重新上傳做好的app提交到app store&#xff0c;結果就出現標題上的錯誤。“No identities are available for signing”。 以后碰到這樣的問題按照下面幾個步驟來做&#xff1a; 進入Distribution -----下載發布證書 -----雙擊安裝-----重啟Xcode就能上傳了 其他細節 如果再…

半連接反連接

半連接&反連接 1. 半連接 半連接返回左表中與右表至少匹配一次的數據行&#xff0c;通常體現為 EXISTS 或者 IN 子查詢。左表驅動右表。只返回左表的數據&#xff0c;右表作為篩選條件。 可以用 EXISTS、 IN 或者 ANY 舉例&#xff1a;表t1和表t2做半連接&#xff0c;t…

匿名方法和Lambda表達式

出于MVVM學習的需要&#xff0c;復習下匿名方法和Lambda表達式&#xff0c;因為之前用的也比較少&#xff0c;所以用的也不是很熟練&#xff0c;Baidu下相關的知識&#xff0c;寫了這個Demo&#xff0c;目標是用簡單的方法展示這個怎么用。 這里偏重的和LINQ中的Lambda表達式 …

爛橘子

Problem Statement: 問題陳述&#xff1a; Given a matrix of dimension r*c where each cell in the matrix can have values 0, 1 or 2 which has the following meaning: 給定尺寸r * C的矩陣&#xff0c;其中矩陣中的每個單元可以具有其具有以下含義的值0&#xff0c;1或2…

android junit 測試程序

http://blog.csdn.net/to_cm/article/details/5704783 Assert.assertEquals(2, t); 斷言轉載于:https://www.cnblogs.com/wjw334/p/3714120.html