在Java中检查一个字符是否为特殊字符

11

可能重复:
JAVA:检查字符串中是否有特殊字符

我是一名初学者程序员,正在寻求帮助确定一个字符是否为特殊字符。我的程序要求用户输入文件名,然后读取文件中的文本,并确定文本中有多少个空格、数字、字母和特殊字符。我已经完成了用于确定空格、数字和字母的代码,但是不确定如何检查一个字符是否为特殊字符。如果您能提供任何帮助,我将不胜感激,如果有什么不清楚的地方,我可以尝试说明。我目前的代码如下:

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

我需要在最后的if语句中放置一些东西来增加specialcharCount。


3
你对“特殊字符”的定义是什么,你希望如何计数? - FThompson
3
根据特殊字符的定义,简单的 else specialCharCount++ 就可以实现。 - Anthony Accioly
!@#¥%……&*—_‘:。><,?/等等,基本上任何不是字母数字或空格的字符,谢谢。 - user1701604
还可以看一下这个链接:https://dev59.com/cXI-5IYBdhLWcg3wj5FG - Anthony Accioly
我尝试了else语句,但它包括所有数字、空格和特殊字符。我该如何做才能仅计算特殊字符? - user1701604
@OP:将 if(Character.isDigit(c))if(Character.isLetter(c)) 替换为 else if(Character.isDigit(c))else if(Character.isLetter(c)),这样只有当字符不是空格、数字或字母时才会进入 else 语句。 - Anthony Accioly
4个回答

17

该方法检查一个字符串是否包含一个特殊字符(根据您的定义)。

/**
 *  Returns true if s contains any character other than 
 *  letters, numbers, or spaces.  Returns false otherwise.
 */

public boolean containsSpecialCharacter(String s) {
    return (s == null) ? false : s.matches("[^A-Za-z0-9 ]");
}

您可以使用相同的逻辑来计算字符串中特殊字符的数量,例如:

/**
 *  Counts the number of special characters in s.
 */

 public int getSpecialCharacterCount(String s) {
     if (s == null || s.trim().isEmpty()) {
         return 0;
     }
     int theCount = 0;
     for (int i = 0; i < s.length(); i++) {
         if (s.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
             theCount++;
         }
     }
     return theCount;
 }

另一个方法是将所有特殊字符放在一个字符串中,然后使用String.contains

/**
 *  Counts the number of special characters in s.
 */

 public int getSpecialCharacterCount(String s) {
     if (s == null || s.trim().isEmpty()) {
         return 0;
     }
     int theCount = 0;
     String specialChars = "/*!@#$%^&*()\"{}_[]|\\?/<>,.";
     for (int i = 0; i < s.length(); i++) {
         if (specialChars.contains(s.substring(i, 1))) {
             theCount++;
         }
     }
     return theCount;
 }

注意:您必须使用反斜杠对反斜杠和"字符进行转义。


上述内容是一般解决此问题的示例。

对于您在问题中所述的确切问题,@LanguagesNamedAfterCoffee提供的答案是最有效的方法。


对于“包含”解决方案,加1分。您忘记在正则表达式中考虑数字。 - Anthony Accioly
不喜欢特殊字符字符串-考虑到国际字符集......我非常喜欢您的第一个解决方案。 - Mizmor
我有些困惑 - 使用正则表达式的解决方案只评估只包含一个数字的字符串。我的意思是,类似于"a@b"这样的字符串不会被"s.matches("[^A-Za-z0-9 ]")"匹配。我认为更合适的另一种版本是检查字符串是否只包含合法字符(请注意星号指示符,它匹配多个字符):s.matches("[A-Za-z0-9 ]*")。有用的链接:https://dev59.com/cXI-5IYBdhLWcg3wj5FG。 - Victor
我认为在你的第二种方法中,应该使用(i+1)作为endIndex,而不仅仅是1。s.substring(i, 1) 应该改为 s.substring(i, i+1) - DesertPride

6
请看 java.lang.Character 类的静态成员方法(isDigit、isLetter、isLowerCase等)。 示例:
String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
   char ch = str.charAt(i);
   if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
      ++specials;
   } else if (Character.isDigit(ch)) {
      ++digits;
   } else if (Character.isSpace(ch)) {
      ++spaces;
   } else {
      ++letters;
   }
}

如果您重构if语句,使字母首先匹配,特殊字符最后匹配,您可以通过仅调用每个建议的“Character”方法一次来更有效地实现相同的结果。此外,请记住,“isSpace”已被弃用,推荐使用“isWhitespace”,这些方法也将计算诸如“\t”,“\n”,“\r”等字符作为空格。 - Anthony Accioly

3
您可以使用正则表达式(regular expressions)来进行操作。
String input = ...
if (input.matches("[^a-zA-Z0-9 ]"))

如果您对“特殊字符”的定义只是指任何不适用于您已有的其他过滤器的内容,则可以简单地添加一个else。同时请注意,在这种情况下,您必须使用else if

if(c == ' ') {
    blankCount++;
} else if (Character.isDigit(c)) {
    digitCount++;
} else if (Character.isLetter(c)) {
    letterCount++;
} else { 
  specialcharCount++;
}

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接