문자열에 ASCII 만 포함되어 있는지 확인할 수 있습니까?
문자가 문자이면 호출이 Character.isLetter(c)
반환 true
됩니다. 그러나 String
ASCII의 기본 문자 만 포함 하는지 빠르게 찾을 수있는 방법이 있습니까?
에서 구아바 이후 19.0, 당신은 사용할 수 있습니다 :
boolean isAscii = CharMatcher.ascii().matchesAllOf(someString);
이것은 더 이상 사용되지 않는 싱글 톤이 아닌 matchesAllOf(someString)
팩토리 메소드에 의존 하는 메소드를 사용합니다 .ascii()
ASCII
여기에 ASCII는 모든 ASCII 문자를 포함 포함 된 인쇄 문자보다 0x20
같은 탭, 줄 바꿈 / 반품 등뿐만 아니라 (공간) BEL
코드 0x07
와 DEL
코드를 0x7F
.
코드 포인트가 이전 버전의 주석에 표시된 경우에도이 코드는 코드 포인트가 아닌 문자를 잘못 사용합니다. 운 좋게도, 값 U+010000
이상의 코드 포인트를 작성하는 데 필요한 문자는 ASCII 범위 밖의 값을 갖는 두 개의 대리 문자를 사용합니다. 따라서이 방법은 이모티콘이 포함 된 문자열의 경우에도 ASCII 테스트에 계속 성공합니다.
ascii()
방법이 없는 이전 구아바 버전의 경우 다음과 같이 작성할 수 있습니다.
boolean isAscii = CharMatcher.ASCII.matchesAllOf(someString);
java.nio.charset.Charset으로 할 수 있습니다 .
import java.nio.charset.Charset;
public class StringUtils {
public static boolean isPureAscii(String v) {
return Charset.forName("US-ASCII").newEncoder().canEncode(v);
// or "ISO-8859-1" for ISO Latin 1
// or StandardCharsets.US_ASCII with JDK1.7+
}
public static void main (String args[])
throws Exception {
String test = "Réal";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
test = "Real";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
/*
* output :
* Réal isPureAscii() : false
* Real isPureAscii() : true
*/
}
}
라이브러리에 의존하지 않고 정규식을 사용하는 또 다른 방법이 있습니다.
이 한 줄을 사용할 수 있습니다 :
text.matches("\\A\\p{ASCII}*\\z")
전체 예제 프로그램 :
public class Main {
public static void main(String[] args) {
char nonAscii = 0x00FF;
String asciiText = "Hello";
String nonAsciiText = "Buy: " + nonAscii;
System.out.println(asciiText.matches("\\A\\p{ASCII}*\\z"));
System.out.println(nonAsciiText.matches("\\A\\p{ASCII}*\\z"));
}
}
문자열을 반복하고 모든 문자의 값이 128 미만인지 확인하십시오.
Java Strings are conceptually encoded as UTF-16. In UTF-16, the ASCII character set is encoded as the values 0 - 127 and the encoding for any non ASCII character (which may consist of more than one Java char) is guaranteed not to include the numbers 0 - 127
Or you copy the code from the IDN class.
// to check if a string only contains US-ASCII code point
//
private static boolean isAllASCII(String input) {
boolean isASCII = true;
for (int i = 0; i < input.length(); i++) {
int c = input.charAt(i);
if (c > 0x7F) {
isASCII = false;
break;
}
}
return isASCII;
}
commons-lang3 from Apache contains valuable utility/convenience methods for all kinds of 'problems', including this one.
System.out.println(StringUtils.isAsciiPrintable("!@£$%^&!@£$%^"));
try this:
for (char c: string.toCharArray()){
if (((int)c)>127){
return false;
}
}
return true;
Iterate through the string, and use charAt() to get the char. Then treat it as an int, and see if it has a unicode value (a superset of ASCII) which you like.
Break at the first you don't like.
private static boolean isASCII(String s)
{
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) > 127)
return false;
return true;
}
It was possible. Pretty problem.
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class EncodingTest {
static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII")
.newEncoder();
public static void main(String[] args) {
String testStr = "¤EÀsÆW°ê»Ú®i¶T¤¤¤ß3¼Ó®i¶TÆU2~~KITEC 3/F Rotunda 2";
String[] strArr = testStr.split("~~", 2);
int count = 0;
boolean encodeFlag = false;
do {
encodeFlag = asciiEncoderTest(strArr[count]);
System.out.println(encodeFlag);
count++;
} while (count < strArr.length);
}
public static boolean asciiEncoderTest(String test) {
boolean encodeFlag = false;
try {
encodeFlag = asciiEncoder.canEncode(new String(test
.getBytes("ISO8859_1"), "BIG5"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodeFlag;
}
}
This will return true if String only contains ASCII characters and false when it does not
Charset.forName("US-ASCII").newEncoder().canEncode(str)
If You want to remove non ASCII , here is the snippet:
if(!Charset.forName("US-ASCII").newEncoder().canEncode(str)) {
str = str.replaceAll("[^\\p{ASCII}]", "");
}
//return is uppercase or lowercase
public boolean isASCIILetter(char c) {
return (c > 64 && c < 91) || (c > 96 && c < 123);
}
참고URL : https://stackoverflow.com/questions/3585053/is-it-possible-to-check-if-a-string-only-contains-ascii
'development' 카테고리의 다른 글
안드로이드 : 텍스트 뷰의 마지막 줄 (0) | 2020.08.04 |
---|---|
통계 : 파이썬의 조합 (0) | 2020.08.04 |
취소 선 텍스트를 만드시겠습니까? (0) | 2020.08.04 |
화면 강제 켜기 (0) | 2020.08.04 |
프로그래밍 방식으로 소프트 키보드 열기 (0) | 2020.08.04 |