简体   繁体   English

如何只接受Java中具有某些字符的String

[英]How to only accept a String with certain characters in Java

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). 我正在尝试创建一个检查字符串的函数,如果它只有某些字符(只有az,AZ,挪威字母å,æ,ø,Å,Æ,Ø,空格和连字符,但我遇到了一些麻烦我试着做你在这里看到的东西,但它没有按照我希望的方式工作(我还没有实现挪威的字母,因为我对如何做到这一点毫无头绪)。

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. 因为它为每个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 只接受那些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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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