從replaceIgnoreCase說起

   昨天寫minidao的替換where and 爲where 這裏因爲沒有辦法判斷用戶傳入的是大寫或者小寫的字符,只能忽略大小寫
最先想到的做法是toLowerCase()單明顯是不可取的,因爲除了sql 關鍵字之外用戶還是有自己的關鍵字,這個肯定是要區分大
小寫的,然後想到的,窮舉這個方法也明顯不靠譜,想,百度了下也沒有什麼好辦法,只有自己寫了,但是自己寫也必須for,然後判斷
大小寫,比較麻煩相當於自己寫個通用方法,這個還是一個比較重要功能,效率必須要考慮的,只能最用用笨辦法,String的API是肯定沒有了,又看了各個Util的,在org.apache.commons.lang.StringUtils 發現了indexOfIgnoreCase這個方法雖然和目標還有一點差距不過已經非常接近了,就出現了下面的代碼
這個是把| and|給刪除了
但是每次都要從0開始索引,就又把代碼改成
這個就不會重複浪費性能了.而且StringUtils.indexOfIgnoreCase得性能很不錯,比我自己寫不知高出幾個檔次.
這裏想要說的
      代碼,如果是通用方法,能調用API的就調用API,org.apache.commons或者guava這裏面的代碼,不知道經過了多少人檢驗以及測試,比我們自己再寫一個方法要優秀的多.
       百度不一定可以百度到你想要的,自己也要多熟悉下API,多看看常用的工具類,如果不是這個,我自己又要寫不知多久
最好說說這個實現類
    
這裏大家可以看到好幾個IF,可能我們寫代碼不會這麼注意,所以經常會造成異常 ,儘量應該先判斷條件,特別是你想寫成工具類.
他這裏沒有做什麼,只是for一下字符串,然後調用String的regionMatches 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public boolean regionMatches(boolean ignoreCase, int toffset,
                           String other, int ooffset, int len) {
        char ta[] = value;
        int to = offset + toffset;
        char pa[] = other.value;
        int po = other.offset + ooffset;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) ||
                (ooffset > (long)other.count - len)) {
            return false;
        }
        while (len-- > 0) {
            char c1 = ta[to++];
            char c2 = pa[po++];
            if (c1 == c2) {
                continue;
            }
            if (ignoreCase) {
                // If characters don't match but case may be ignored,
                // try converting both characters to uppercase.
                // If the results match, then the comparison scan should
                // continue.
                char u1 = Character.toUpperCase(c1);
                char u2 = Character.toUpperCase(c2);
                if (u1 == u2) {
                    continue;
                }
                // Unfortunately, conversion to uppercase does not work properly
                // for the Georgian alphabet, which has strange rules about case
                // conversion.  So we need to make one last check before
                // exiting.
                if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                    continue;
                }
            }
            return false;
        }
        return true;
    }

最好那個比較感覺是點睛之作,java都怕自己的API出問題,我們自己更應該做一些參數的校驗 


我的開源:點擊打開鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章