Czy w Javie można sprawdzić, czy ciąg znaków jest tylko ASCII?

Znak.isLetter (c) zwraca true, jeśli znak jest literą. Ale czy istnieje sposób, aby szybko znaleźć, czy ciąg zawiera tylko podstawowe znaki ASCII?

 93
Author: Steve Kuo, 2010-08-27

11 answers

Używając guawa , możesz po prostu napisać:

boolean isAscii = CharMatcher.ASCII.matchesAllOf(someString);

Od Guava 19.0 NA, należy użyć CharMatcher.ascii() zamiast tego.

 111
Author: ColinD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 01:07:23

Możesz to zrobić za pomocą Javy.nio.charset.Charset .

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class StringUtils {

  static CharsetEncoder asciiEncoder = 
      Charset.forName("US-ASCII").newEncoder(); // or "ISO-8859-1" for ISO Latin 1

  public static boolean isPureAscii(String v) {
    return asciiEncoder.canEncode(v);
  }

  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
      */
  }
}

Detect non - ASCII znak w łańcuchu

 85
Author: RealHowTo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-27 14:37:44

Tutaj jest inny sposób nie zależny od biblioteki, ale za pomocą wyrażenia regularnego.

Możesz użyć tej pojedynczej linii:

text.matches("\\A\\p{ASCII}*\\z")

Cały przykładowy program:

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"));
    }
}
 66
Author: Arne Deutsch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-27 14:40:50

Iteruj przez łańcuch i upewnij się, że wszystkie znaki mają wartość mniejszą niż 128.

Ciągi Javy są koncepcyjnie zakodowane jako UTF-16. W UTF-16 zestaw znaków ASCII jest kodowany jako wartości 0 - 127, a kodowanie dowolnego znaku spoza ASCII (który może składać się z więcej niż jednego znaku Java) gwarantuje, że nie będzie zawierać liczb 0-127

 46
Author: JeremyP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-27 15:37:23

Lub skopiujesz kod z klasy IDN .

// 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;
}
 15
Author: Zarathustra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-28 08:14:59

Commons-lang3 z Apache zawiera cenne narzędzia / metody wygody dla wszystkich rodzajów "problemów", w tym tego.

System.out.println(StringUtils.isAsciiPrintable("!@£$%^&!@£$%^"));
 8
Author: fjkjava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-13 21:06:24

Spróbuj tego:

for (char c: string.toCharArray()){
  if (((int)c)>127){
    return false;
  } 
}
return true;
 5
Author: pforyogurt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-28 22:02:43

Iteruje przez łańcuch znaków i używa charAt (), aby uzyskać znak. Następnie potraktuj go jako int i sprawdź, czy ma wartość unicode (superset ASCII), którą lubisz.

Przerwa na początku nie lubisz.

 3
Author: Thorbjørn Ravn Andersen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-27 14:21:42
private static boolean isASCII(String s) 
{
    for (int i = 0; i < s.length(); i++) 
        if (s.charAt(i) > 127) 
            return false;
    return true;
}
 2
Author: fdsfdsfdsfds,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-26 14:13:18
//return is uppercase or lowercase
public boolean isASCIILetter(char c) {
  return (c > 64 && c < 91) || (c > 96 && c < 123);
}
 0
Author: Lukas Greblikas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-14 23:13:01

To było możliwe. Niezły 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;
    }
}
 0
Author: user3614583,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-14 23:47:24