Home  >  Article  >  php教程  >  将字符串中的标点符号过滤掉

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

PHP中文网
PHP中文网Original
2016-05-25 16:58:522275browse

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

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();  
    }

                   


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn