java中如何检查字符串是否有全角字符

问题描述 投票:0回答:6

任何人都可以建议我如何检查

String
中是否包含全角字符?全角字符是特殊字符。

字符串中的全角字符:

abc@gmail.com

字符串中的半角字符:

[电子邮件受保护]

    
java string character special-characters
6个回答
5
投票

Java

至于你的半宽
public static boolean isAllFullWidth(String str) { for (char c : str.toCharArray()) if ((c & 0xff00) != 0xff00) return false; return true; } public static boolean areAnyFullWidth(String str) { for (char c : str.toCharArray()) if ((c & 0xff00) == 0xff00) return true; return false; }

和可能的

'.'
。首先将它们去掉并进行替换:

'_'

正则表达式

或者,如果您想使用正则表达式进行测试,那么这是全角的实际字符范围:

String str="abc@gmail.com"; if (isAllFullWidth(str.replaceAll("[._]",""))) //then apart from . and _, they are all full width

所以该方法看起来像:

[\uFF01-\uFF5E]

您可以向其中添加其他角色,因此无需删除它们:

public static boolean isAllFullWidth(String str) { return str.matches("[\\uff01-\\uff5E]*"); }



2
投票
public static boolean isValidFullWidthEmail(String str) { return str.matches("[\\uff01-\\uff5E._]*"); }

由于字母表 (a-z) 的 unicode 是

UNICODE
,因此您可以轻松区分两者

97-122

用于输入

String str="abc@gmail.com"; System.out.println((int)str.charAt(0));

输出

abc@gmail.com



2
投票

65345



0
投票
如果以下语句返回 true,则

str 将包含全角字符:

布尔标志 = str.matches("\W");


0
投票

全角:> 1 字节(2,3,4.. 字节)

->比较:字符串长度==字节长度

public static final String FULL_WIDTH_CHARS = "AaBbCcDdEeFfGgHhIiJj" + "KkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; public static boolean containsFullWidthChars(String str) { for(int i = 0; i < FULL_WIDTH_CHARS.length(); i++) { if(str.contains(String.valueOf(FULL_WIDTH_CHARS.charAt(i)))) { return true; } } return false; }



0
投票

有了这些知识,我们现在可以使用这两种方法轻松地来回转换它们。

这会将相关的 ascii 字符转换为宽 Unicode 版本。

String strCheck = "abc@gmail.com"; if (str.length() != str.getBytes().length) { // is Full Width } else { // is Half Width }

这会将宽 Unicode 字符转换回常规 ascii。

public static char toWideCharacter(char c) { // Check if they are the characters that are convertible. if (c > 0x20 && c < 0x7F) // Remove the offset and make sure we set these bytes FF00 return (char) (c - 0x20 | 0xFF00); else return c; }

额外学分:

这是一个生成字符串并来回转换它们以检查我们脆弱的理智的示例。

public static char fromWideCharacter(char c) { // We can use this statement alone to check if they are wide characters. if (c > 0xFF00 && c < 0xFF5F) // Add the offset and mask the bits we want to keep. return (char) (c + 0x20 & 0xFF); else return c; }

© www.soinside.com 2019 - 2024. All rights reserved.