首頁  >  文章  >  php教程  >  将字符串中的标点符号过滤掉

将字符串中的标点符号过滤掉

PHP中文网
PHP中文网原創
2016-05-25 16:58:522305瀏覽

开发中我们有可能会遇到这种情况,就是将字符串中的某个字符去掉

PHP代码

@Test  
    public void test() {  
        String d = trimPunctuation2("你,好oewefo,21.2!;:、1?dsf");  
        System.out.println(d);  
    }  
  
    // 将字符串中的标点符号过滤掉  
    public static String trimPunctuation2(String str) {  
        String punct[] = { ",", ".", "!", "?", ";", ":", ",", "。", "!", "?",  
                ";", ":", "、" };  
        List<String> punctList = Arrays.asList(punct); // 将String数组转List集合  
        StringBuilder result = new StringBuilder();  
        for (int i = 0; i < str.length(); i++) {  
            Character c = str.charAt(i);  
            if (punctList.contains(c.toString())) {  
  
            } else {  
                result.append(str.charAt(i));  
            }  
        }  
  
        return result.toString();  
    }  
  
    // 将字符串中的标点符号过滤掉  
    public static String trimPunctuation(String str) {  
        StringBuilder result = new StringBuilder();  
        for (int i = 0; i < str.length(); ++i) {  
            char punct[] = { &#39;,&#39;, &#39;.&#39;, &#39;!&#39;, &#39;?&#39;, &#39;;&#39;, &#39;:&#39;, &#39;,&#39;, &#39;。&#39;, &#39;!&#39;, &#39;?&#39;,  
                    &#39;;&#39;, &#39;:&#39;, &#39;、&#39; };  
            boolean need_filter = false;  
            for (int j = 0; j < punct.length; ++j) {  
                if (punct[j] == str.charAt(i)) {  
                    need_filter = true;  
                    break;  
                }  
            }  
  
            if (!need_filter) {  
                result.append(str.charAt(i));  
            }  
        }  
  
        return result.toString();  
    }

                   


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn