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

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

PHP中文网
PHP中文网原创
2016-05-25 16:58:522321浏览

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

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