Possible Duplicate:
JAVA: check a string if there is a special character in it
I am a novice programmer and am looking for help determining if a character is a special character. My program asks the user to input the name of a file, and the program reads the text in the file and determines how many blanks spaces, digits, letters, and special characters are in the text. I have the code completed to determine the blanks, digits, and letters, however am unsure of how to check if a character is a special character. Any help you can offer is appreciated and if something was not clear enough I can try to elaborate. My code so far is:
import java.util.Scanner;
import java.io.*;
public class TextFile{
public static void main(String[] args){
Scanner input = new Scanner (System.in);
String fileName;
boolean goodName = false;
int blankCount = 0;
int letterCount = 0;
int digitCount = 0;
int specialcharCount = 0;
String currentLine;
char c;
Scanner lineFile= null;
FileReader infile;
System.out.println("Please enter the name of the file: ");
fileName = input.nextLine();
while (!goodName) {
try{
infile = new FileReader(fileName);
lineFile = new Scanner(infile);
goodName= true;
}
catch(IOException e) {
System.out.println("Invalid file name, please enter correct file name: ");
fileName=input.nextLine();
}
}
while (lineFile.hasNextLine()){
currentLine = lineFile.nextLine();
for(int j=0; j<currentLine.length();j++){
c=currentLine.charAt(j);
if(c== ' ') blankCount++;
if(Character.isDigit(c)) digitCount++;
if(Character.isLetter(c)) letterCount++;
if() specialcharCount++;
}
}
}
}
I need something to put in the if statement at the end to increment specialcharCount.
This method checks if a String contains a special character (based on your definition).
You can use the same logic to count special characters in a string like this:
Another approach is to put all the special chars in a String and use String.contains:
NOTE: You must escape the backslash and
"
character with a backslashes.The above are examples of how to approach this problem in general.
For your exact problem as stated in the question, the answer by @LanguagesNamedAfterCoffee is the most efficient approach.
What I would do:
That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.
ASCII chart: http://www.gophoto.it/view.php?i=http://i.msdn.microsoft.com/dynimg/IC102418.gif#.UHsqxFEmG08
Take a look at class
java.lang.Character
static member methods (isDigit, isLetter, isLowerCase, ...)Example:
You can use regular expressions.
If your definition of a 'special character' is simply anything that doesn't apply to your other filters that you already have, then you can simply add an
else
. Also note that you have to useelse if
in this case: