Home > php教程 > PHP源码 > body text

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

PHP中文网
Release: 2016-05-25 16:58:52
Original
2326 people have browsed it

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

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

                   


Related labels:
php
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template