/**
* 假如有字符串“6sabcsssfsfs33” ,用最有快速的方法去掉字符“ab3 “
*
*/
- // =======第一种方法======
- public static void replaceString(String str) {
- char myChar[] = str.toCharArray();
- int len = myChar.length;
- String tempStr = "";
- for (int i = 0; i < len; i++) {
- if ('a' == myChar[i] || 'b' == myChar[i] || '3' == myChar[i]) {
- myChar[i] = ' ';
- }
- String temp = "";
- temp = myChar[i] + "";
- tempStr += temp.trim();
- }
- System.out.println(tempStr);
- }
- // =======第二种方法======
- public static void replaceString2(String str) {
- char s[] = str.toCharArray();
- int len = str.length();
- char string[] = new char[14];
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < len; i++) {
- if ('a' != s[i] && 'b' != s[i] && '3' != s[i]) {
- // string[i] = s[i];
- sb.append(s[i]);
- }
- // String temp = null;
- // temp = string[i] + "";
- // sb.append(temp.trim());
- }
- System.out.println(sb.toString());
- }
- // =======第三种方法======
- public static String replaceString3(String des, String reg) {
- StringBuilder buf = new StringBuilder(des.length());
- char[] chars = des.toCharArray();
- char[] regchars = reg.toCharArray();
- for (char c : chars) {
- boolean b = true;
- for (char regchar : regchars) {
- if (c == regchar) {
- b = false;
- break;
- }
- }
- if (b)
- buf.append(c);
- }
- return buf.toString();
- }
- // =======第四种方法======
- public static void replaceString4(String str) {
- // 指定为字符串的正则表达式必须首先被编译为此类的实例
- Pattern pattern = Pattern.compile("[^a|b|3]"); // ^非 ; 边界匹配器"^"行的开头
- // 然后,可将得到的模式用于创建 Matcher
- // 对象,依照正则表达式,该对象可以与任意字符序列匹配。执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。
- Matcher matcher = pattern.matcher(str);
- String temp = "";
- while (matcher.find()) {
- temp += matcher.group();// 返回由以前匹配操作所匹配的输入子序列
- }
- System.out.println(temp);
- }
- // =======第五种方法======
- public static void replaceString5(String str) {
- StringBuffer sb = new StringBuffer();
- Scanner scanner = new Scanner(str);
- // 匹配扫描
- scanner.findInLine("(//S*)ab(//S*)33(//S*)");
- // 返回此扫描器所执行的最后扫描操作的匹配结果
- MatchResult ms = scanner.match();
- for (int i = 1; i < ms.groupCount(); i++) { // 注意i的初始值
- sb.append(ms.group(i));
- }
- scanner.close();
- System.out.println(sb);
- }
- // =======第六种方法======
- public static String replaceString6(String str, String toRemove) {
- boolean[] removeMap = new boolean[255];
- char[] originChars = str.toCharArray();
- char[] todoChars = toRemove.toCharArray();
- char[] destChars = null;
- int strLen = 0;
- // build toRemove chars map
- for (int i = 0; i < todoChars.length; i++) {
- removeMap[(todoChars[i] & 0xFF)] = true;
- }
- for (int i = 0; i < originChars.length; i++) {
- if (removeMap[(originChars[i] & 0xff)]) {
- if (destChars == null) {
- destChars = new char[originChars.length - 1];
- System.arraycopy(originChars, 0, destChars, 0, i);
- }
- } else {
- if (destChars != null) {
- destChars[strLen] = originChars[i];
- }
- strLen++;
- }
- }
- return destChars == null ? str : new String(destChars, 0, strLen);
- }