for (int i = 0; i < d.getFornavn().length(); i++) {
char c = d.getFornavn().charAt(i);
if ((c > 'a' && c < 'z') || (c > 'A' && c < 'Z') || ( c == ' ' || c == '-')) {
flag = true;
}
}
Hi! I'm trying to make a function that checks a string if it only has certain characters (only az, AZ, the norwegian letters å,æ,ø,Å,Æ,Ø, whitespace and hyphen, but I'm having some trouble with that. I tried doing what you see here, but it's not working how I hoped it would (I didn't implement the norwegian letters yet, because I'm clueless on how to do that).
I'm starting to think there must be a simpler way to check for this, but I haven't heard about anything.
Any thoughts?
您可以使用正则表达式:
flag = d.getFornavn().matches("[a-zA-zåæøÅÆØ -]+");
The approach you are using will give result based on last character of your string or only one character . Since it is setting flag for each char. To reject all invalid strings you can simply
bool flag = true;
for (int i = 0; i < d.getFornavn().length(); i++) {
char c = d.getFornavn().charAt(i);
if ((!c > 'a' && c < 'z') && !(c > 'A' && c < 'Z') && ( c != ' ' || c != '-')) {
flag = false;
break;
}
}
Accept only those strings which flag true
You could search on a string
public static void main(String[] args) {
String s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ - åæøÅÆØ";
String yourstr = "Ø123456";
System.out.println(myfunc(s, yourstr));
}
private static boolean myfunc(String s, String yourstr) {
for (int i = 0; i < yourstr.length(); i++) {
char c = yourstr.charAt(i);
if (s.indexOf(c) > 0) {
return true;
}
}
return false;
}
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.