0

所以我想知道如何检查用户输入的字符串是否有多个空格,如果单词之间确实有多个空格,我希望重新提示用户输入。我正在使用 do-while 循环。这是格式:

Scanner scanner01 = new Scanner(System.in);
String inputLast;
do {
    System.out.println("Enter a valid LAST name: ");
    inputLast = scanner01.nextLine();
} while()
4

3 回答 3

0

一种解决方案是(基于此答案):

   Scanner scanner01 = new Scanner(System.in);
   String inputLast;
   do {
       System.out.println("Enter a valid LAST name: ");
       inputLast = scanner01.nextLine();
       if(inputLast.length() - inputLast.replaceAll(" ", "").length() <= 1){
           break;
       }
   } while(true);
于 2013-07-22T15:27:56.117 回答
0
String str = "Sam  ple";
Pattern pattern = Pattern.compile("\\s{2,}");
Matcher matcher = pattern.matcher(str);
boolean check = matcher.find();
于 2013-07-22T15:27:59.693 回答
0

有关如何用单个空格替换多个空格的说明,请阅读how-to-replace-2-or-more-spaces-with-single-space-in-string

于 2013-07-22T15:11:15.693 回答