首页 > 解决方案 > 如何正确迭代两个循环

问题描述

我想将我的字符串替换为其他字符串但没有很多符号。例如,我有“我想成为!#$%@!_”,它应该返回“Iwanttobe”。这以某种方式起作用,但不幸的是它迭代了第一个循环(第一个字符),然后迭代了整个第二个循环。我希望它遍历所有第一个,然后遍历所有第二个,并基于此将字符添加到我的新表中

这是我的方法:

public static List<Character> count (String str){

    char[] chars = str.toCharArray();
    List<Character> charsWithOutSpecial = new ArrayList<>();
    char[] specialChars = {' ','!','"','#','$','%','&','(',')','*','+',',',
            '-','.','/',':',';','<','=','>','?','@','[',']','^','_',
            '`','{','|','}','~','\\','\''};

    for (int i = 0; i < specialChars.length; i++) {
        for (int j = 0; j < chars.length; j++) {
            if(specialChars[i] != chars[j]){
                charsWithOutSpecial.add(chars[j]);
            }
        }
    }
    return charsWithOutSpecial;
}

标签: javaarraysloopsfor-loopchar

解决方案


这应该做的工作:

str = str.replaceAll("[^A-Za-z0-9]", ""); // replace all characters that are not numbers or characters with an empty string.

推荐阅读