欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

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

程序员文章站 2022-04-17 22:13:56
...
开发中我们有可能会遇到这种情况,就是将字符串中的某个字符去掉

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[] = { ',', '.', '!', '?', ';', ':', ',', '。', '!', '?',  
                    ';', ':', '、' };  
            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();  
    }
相关标签: PHP