有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何正确迭代两个循环

我想将我的字符串替换为其他字符串,但没有很多符号。例如,我有“我想成为!#$%@!”,它应该返回“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;
}

共 (3) 个答案

  1. # 1 楼答案

    您可以这样修复您的方法:

    public static List<Character> count (String str){
    
        char[] chars = str.toCharArray();
        List<Character> charsWithOutSpecial = new ArrayList<>();
        char[] specialChars = {' ','!','"','#','$','%','&','(',')','*','+',',',
                '-','.','/',':',';','<','=','>','?','@','[',']','^','_',
                '`','{','|','}','~','\\','\''};
    
        for (int i = 0; i < chars.length; i++) {
            boolean isCharValid = true;
            // iterating over the special chars
            for (int j = 0; j < specialChars.length; j++) { 
                if(specialChars[j] == chars[i]){
                    // we identified the char as special 
                    isCharValid = false; 
                }
            }
    
            if(isCharValid){
                charsWithOutSpecial.add(chars[i]);
            }
        }
        return charsWithOutSpecial;
    }
    
  2. # 2 楼答案

    你想要的正则表达式可能是[^a-zA-Z]

    但是你也可以用两个循环来实现

    StringBuilder str2 = new StringBuilder();
      for (int j = 0; j < chars.length; j++) {
        boolean special = false;
        for (int i = 0; i < specialChars.length; i++) {
            if(specialChars[i] == chars[j]){
                special = true;
                break;
            }
        }
        if (!special) str2.append(chars[j]);
    }
    
  3. # 3 楼答案

    这应该可以做到:

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