【问题标题】:How to properly iterate over two loops如何正确迭代两个循环
【发布时间】:2021-08-09 17:10:34
【问题描述】:

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

【问题讨论】:

  • 必须是循环吗?您可以通过使用.replaceAll() 和正则表达式来解决此问题
  • 我正在尝试使用正则表达式,但我找不到“正确”的正则表达式

标签: java arrays loops for-loop char


【解决方案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;
}

【讨论】:

  • 你可以把specialChars数组变成ArrayList,然后使用.contains()方法来简化事情。
  • 完全同意,但有时问题更“深”,OP可能想知道如何纠正他的方法:)
【解决方案2】:

这应该可以完成工作:

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

【讨论】:

    【解决方案3】:

    你想要的正则表达式可能是 [^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]);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2016-09-26
      • 2014-12-24
      • 1970-01-01
      相关资源
      最近更新 更多