简体   繁体   English

Java字符串中的特殊字符

[英]Special characters in a java string

I am trying to write a code to find the special characters in a java string. 我正在尝试编写代码以查找Java字符串中的特殊字符。

Special characters are a-zA-Z.?@;'#~!£$%^&*()_+-=¬`,./<> 特殊字符是a-zA-Z。?@;'#〜!£$%^&*()_ +-=¬`,。/ <>

Please help me to understand and write how can I implement this. 请帮助我理解和编写如何实现此功能。

Thank you 谢谢

You can create a char array from a String. 您可以从字符串创建char数组。

String string = "test";
char[] charArray = string.toCharArray();

Then you can loop through all the characters: 然后,您可以循环浏览所有字符:

for(char character: charArray){
    //check if the character is special and do something with it, like adding it to an List.
}

You can use a Scanner to find the invalid characters in your String: 您可以使用扫描仪在字符串中查找无效字符:

/* Regex with all character considered non-special */
public static final String REGULAR_CHARACTERS = "0-9a-z";

public static String specialCharacters(String string) {
    Scanner scanner = new Scanner(string);
    String specialCharacters= scanner.findInLine("[^" + REGULAR_CHARACTERS  + "]+");
    scanner.close();
    return specialCharacters;
}

The findInLine returns a String with all characters not included in the constant (all special characters). findInLine返回一个字符串,其中所有字符不包含在常量中(所有特殊字符)。 You need to setup the constant with all the characters that you consider non-special. 您需要使用您认为非特殊的所有字符来设置常数。

Alternatively, if you want to setup only the characters you want to find, you can modify the example above with: 另外,如果您只想设置要查找的字符,则可以使用以下方法修改上面的示例:

public static final String SPECIAL_CHARACTERS = "a-zA-Z.?@;'#~!£$%^&*()_+-=¬`,./<>";
....
String specialCharacters= scanner.findInLine("[" + SPECIAL_CHARACTERS + "]+");
....

The characters used in the constants need to be scaped as usual for regular expressions. 常量中使用的字符通常需要对正则表达式进行转义。

For example, to add the ] character, you need to use \\\\] 例如,要添加]字符,您需要使用\\\\]

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

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