简体   繁体   中英

How to properly iterate over two loops

I want to replace my string into other string but without many signs. For example I have "I want to be.#$%@,_" and it should return "Iwanttobe", And that works somehow. but unfortunately it iterates first loop(first character), then iterates over the entire second loop. And I would like it to iterate over all of the first and then all of the second and add characters to my new table based on that

This is my method:

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;
}

This should do the work:

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

You can fix your method like this:

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;
}

The regex you want is probably [^a-zA-Z]

But you can also do this using two loops

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM