简体   繁体   中英

Counting number of special characters in a given String

I'm trying to make a program that will count the special characters in a given string. But it is not working. Here's my code.

public static final String []specialChars = {"!", "@", "#", "$", "%", "^", "&", "*", "(", ")",
                                             "[", "]", "|", ";", "'", ",", ".", "/", "{", "}", 
                                             "\\", ":", "\"", "<", ">", "?" };

I used array because i'm trying to trace the matched special character in a String. So I decided to do the loop.

int specialCharCount = 0;
        for ( int x = 0; x < specialChars.length ; ++x) {
               specialCharCount = password.length() - password.replaceAll("\\specialChars[x]", "").length();
           }
           System.out.print(" and " + specialCharCount + " special characters.\n\n");

It is running but it gives me this output:

and 0 special characters.

The problem you have is that you only consider the number of the last character. I suspect you want the sum of all the special character counts.

for( int x = 0; x < specialChars.length ; ++x) {
    specialCharCount += password.length() 
                    - password.replaceAll("\\" + specialChars[x], "").length();
}

BTW stepping through your code in you debugger would have found that pretty quickly.

How about.

String SPECIAL_CHARS_REGEX = "[!@#$%^&*()\\[\\]|;',./{}\\\\:\"<>?]";

int specials = password.split(SPECIAL_CHARS_REGEX, -1).length - 1;

There are few issues in the code that I see

  1. += - I think you want to increase the count every time. Having = in the code will assign the count of the last special character in your string ("?")
  2. password.replaceAll() will not modify the original string. String in java are immutable. you will have to assign the return referce to itself again.

    password = password.replaceAll("REPLACING STRING", "REPLACED BY STRING");

  3. The first parameter in the following code should not be password.replaceAll("\\\\specialChars[x]", "") within quotes. In your case it is taken as string literal rather than the actual value of the specialChars[x].

    There is a difference between "specialChars[x]" and specialChars[x]

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