Than
Than

Reputation: 21

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

Upvotes: 0

Views: 59

Answers (3)

Most Noble Rabbit
Most Noble Rabbit

Reputation: 2776

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

Upvotes: 1

Renis1235
Renis1235

Reputation: 4700

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.

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

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

Upvotes: 1

Related Questions