如何检查字符串是否有空格

时间:2014-03-06 03:26:11

标签: java space

有人可以向我展示如何检查字符串中SPECIFIC数量的空格的代码。

示例:用户输入的字符串需要正好有3个空格,例如" 0 4 0 1"我需要一个代码来检查每个数字之间是否有空格。

以下是我的尝试:

String guessedSpacesCheck = "[0-9]+";
boolean b2 = guessedSpaces.matches(guessedSpacesCheck);
int totalSpace=guessedSpaces.split(" ").length-1;

boolean isSpaceValid = totalSpace==whiteSpace;

while (b2==false && isSpaceValid==false)
{
    System.out.println("Your input is not valid. Try again.");
    System.out.print("Please enter the letter you want to guess: ");
    letterGuess = keyboard.next().charAt(0);

    System.out.print("Please enter the spaces you want to check (separated by spaces): ");
    guessedSpaces = guessSpace.nextLine();

    guessedSpaces.matches(guessedSpacesCheck);
    if (guessedSpaces.matches(guessedSpacesCheck)==true && isSpaceValid==true)
    {
        b2=true;
        isSpaceValid=true;
    }
}

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式了解输入了多少whitespaces个用户:

Scanner sc = new Scanner(System.in);
System.out.println("Enter word with white-spaces:");
String str = sc.nextLine();
int totalSpace = str.split(" ").length-1;
System.out.println("total white-spaces is:"+totalSpace);

修改:您可以通过更改while这样的条件来解决问题:

 while(!(guessedSpaces.replaceAll("\\d","").length()==3 && guessedSpaces.split(" ").length-1==3)){
    .....
    .....
    System.out.println("Enter word with white-spaces:");
    guessedSpaces = keyboard.nextLine();
}

答案 1 :(得分:0)

 function check(evt) {
    var id= document.getElementById('Id').value;
    if(evt.keyCode == 32){
        alert("Sorry, you are not allowed to enter any spaces");    
        evt.returnValue = false;
        document.getElementById('Id').value='';     
       return false;
        }