is Ascii - Java java.lang

Java examples for java.lang:String UTF

Description

is Ascii

Demo Code

/*/* w w w  .j  a v a 2  s .  c o  m*/
 * This program is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
 * Foundation.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
 * or from the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * Copyright (c) 2006 - 2016 Pentaho Corporation..  All rights reserved.
 */
//package com.java2s;

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class Main {
    /**
     * @param aString
     * @return true if the provided string is completely within the US-ASCII character set.
     */
    public static boolean isAscii(String aString) {
        return isWithinCharset(aString, "US-ASCII"); //$NON-NLS-1$
    }

    /**
     * @param aString
     * @param charsetTarget
     * @return true if the provided string is completely within the target character set.
     */
    public static boolean isWithinCharset(String aString,
            String charsetTarget) {
        byte[] stringBytes = aString.getBytes();
        CharsetDecoder decoder = Charset.forName(charsetTarget)
                .newDecoder();
        try {
            decoder.decode(ByteBuffer.wrap(stringBytes));
            return true;
        } catch (CharacterCodingException ignored) {
            //ignored
        }
        return false;
    }
}

Related Tutorials