【问题标题】:How do I check for special characters in a String[Java]?如何检查字符串 [Java] 中的特殊字符?
【发布时间】:2021-05-24 00:32:58
【问题描述】:

我正在创建一个主机游戏。我希望玩家能够选择自己的用户名。拥有像 .-|\12b-}| 这样的用户名真的很奇怪。我希望能够检查用户名中是否包含“特殊字符”。如果玩家的用户名中有特殊字符,我希望系统打印出一条消息(例如:请更改您的用户名)。我不希望代码只是replace 字母。

这是一个示例(如果您有答案,请按照此操作):

import java.util.Scanner; 
class StackOverflowExample {
  public static void main(String[] args) {
    System.out.println("Welcome New Player! What will your name be?");
    Scanner userInteraction = new Scanner(System.in);
    String userInput = userInteraction.nextLine();
    System.out.println("Welcome " + userInput + "!");
  }
}

输出

你可以明白为什么这会非常奇怪..

我希望能够扫描:

String userInput = userInteraction.nextLine();

对于任何奇怪的字符。 我将如何扫描字符串?

【问题讨论】:

  • 我相信扫描器可以接受正则表达式作为参数来验证 next() 输入。 "a-zA-Z0-9_" 将过滤带有下划线等的字母数字字符。
  • 这里的独特性似乎不是一个因素......
  • @VLAZ 唯一字符是“/”或“%”之类的字符
  • 那些被称为“特殊字符”。术语“唯一”几乎完全意味着编程中的“不重复”。因此,字符串 "abc" 包含唯一字符,但 "abca" 不包含,因为 "a" 出现了两次。
  • @VLAZ 谢谢,现在改了。

标签: java string console java.util.scanner user-input


【解决方案1】:

试试这个。如果提供的不是字母,它会继续提示输入用户名。不允许使用 Battle101 或 ~Hello~ 等用户名。

Scanner userInteraction = new Scanner(System.in);
String userInput = "";
while (true) {
    System.out.println("Welcome New Player! What will your name be?");
    userInput = userInteraction.nextLine();
    if (userInput.matches("[a-zA-Z]+")) { // check that the input only contains letters
       // okay so exit loop
        break;
    }
    // else explain the problem and reprompt.
    System.out.println("Only alphabetic characters are permitted.\nPlease try again.");
}
System.out.println("Welcome " + userInput + "!");

【讨论】:

  • 正是我想要的! “[a-zA-Z]+”中的“加号”在做什么?是多余的吗?
【解决方案2】:

已编辑为具有正确的 java 代码

您可以检查字符串中每个字母的含义,方法是使用 int-asted charAt 调用返回 # 字符是 ASCII [参见此处] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt)

public static boolean isAlphaNumeric(String str) {
  int code, i, len;
  len = str.length();
  for (i = 0; i < len; i++) {
    code = (int) str.charAt(i);
    if (!(code > 47 && code < 58) && // numeric (0-9)
        !(code > 64 && code < 91) && // upper alpha (A-Z)
        !(code > 96 && code < 123)) { // lower alpha (a-z)
      return false;
    }
  }
  return true;
};
public static void main(String[] args) {
   String userInput = userInteraction.nextLine();
   if(isAlphaNumeric(userInput )){
       System.out.println("Welcome New Player! What will your name be?");
       Scanner userInteraction = new Scanner(System.in);
       String userInput = userInteraction.nextLine();
       System.out.println("Welcome " + userInput + "!");
   }
   else{
      System.out.println("Change your name from" + userInput + "!");
   }}

【讨论】:

  • 嗨@StarshipladDev,我想澄清一下这是Java而不是JavaScript。您输入的代码是 JavaScript
  • @FairOPShotgun ,我已经更新了,你可以将一个 char 值转换为 int 以获得相同的 ASCII 值
猜你喜欢
  • 2016-01-14
  • 2013-11-27
  • 2011-05-29
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 2019-02-09
相关资源
最近更新 更多