简体   繁体   中英

How to set a character limit in Java

If I want to make a simple password checker in java and lets say I have a string and I want to count the characters in it, then make sure that it is above six, what would I do?

Your can call length() method on String object. It returns length of that string.

if (str.length() <= 6) //or < 7
    //do something
else
    //do something

You can not explicitly set character limit in String object.

Well, just use length() function that's built-in for String

String string = "Hello World!";
if(string.length() > 6) {
    //TODO
}

The only way I know to enforce the length of a password upon input is as follows:

  • the regex finds the first occurrence of any password over 5 characters that does not contain white space.
Scanner s = new Scanner(System.in);
String pwd = "";
for (int i = 0; i < 10; i++) {
    pwd = s.findInLine("[^\\s]{6,}");
    if (pwd != null) {
        break;
    }
    String attempt = s.nextLine();
    System.out.println(attempt + " -- Invalid password");
}
System.out.println("Valid password = " + pwd);

Note that this solution tries to meet your requirement but is not necessarily better than those answers that suggested using String.length()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM