Java Tutorial/Data Type/Character Data Type
Содержание
- 1 ASCII character handling functions
- 2 Assign int value to char variable
- 3 Character: is Lower Case
- 4 Character: is Upper Case
- 5 char variables behave like integers
- 6 Checks if the string contains only ASCII printable characters.
- 7 Checks whether the character is ASCII 7 bit.
- 8 Checks whether the character is ASCII 7 bit alphabetic.
- 9 Checks whether the character is ASCII 7 bit alphabetic lower case.
- 10 Checks whether the character is ASCII 7 bit alphabetic upper case.
- 11 Checks whether the character is ASCII 7 bit control.
- 12 Checks whether the character is ASCII 7 bit numeric.
- 13 Checks whether the character is ASCII 7 bit numeric and character.
- 14 Checks whether the character is ASCII 7 bit printable.
- 15 Compare Two Java char Arrays
- 16 compare two objects of Character
- 17 Convert character to digit with Character.digit
- 18 Convert from ASCII code to String
- 19 Convert from integer to ASCII code (byte)
- 20 Convert string to char array
- 21 Copy char array to string
- 22 Count letters in a String
- 23 Demonstrate several Is... methods.
- 24 Determines if the specified string is permissible as a Java identifier.
- 25 Determining a Character"s Unicode Block
- 26 Determining If a String Is a Legal Java Identifier
- 27 Display printable Characters
- 28 Escape Sequence Characters
- 29 Is character a digit, letter, white space, lower case or upper case character
- 30 isDigit(): true if the argument is a digit (0 to 9), and false otherwise.
- 31 isLetterOrDigit(): true if the argument is a letter or a digit, and false otherwise.
- 32 isLetter(): true if the argument is a letter, and false otherwise.
- 33 is White space
- 34 Java char: char is 16 bit type and used to represent Unicode characters. Range of char is 0 to
- 35 Max and Min values of datatype char
- 36 Plus one to char variable
- 37 Store unicode in a char variable
- 38 Storing Characters
- 39 Thansform an array of ASCII bytes to a string. the byte array should contains only values in.
- 40 To extract Ascii codes from a String
- 41 Utility methods for ASCII character checking.
- 42 Validate if a String contains only numbers
ASCII character handling functions
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class implements some basic ASCII character handling functions.
*
* @author dac@eng.sun.ru
* @author James Todd [gonzo@eng.sun.ru]
*/
public final class Ascii {
/*
* Character translation tables.
*/
private static final byte[] toUpper = new byte[256];
private static final byte[] toLower = new byte[256];
/*
* Character type tables.
*/
private static final boolean[] isAlpha = new boolean[256];
private static final boolean[] isUpper = new boolean[256];
private static final boolean[] isLower = new boolean[256];
private static final boolean[] isWhite = new boolean[256];
private static final boolean[] isDigit = new boolean[256];
/*
* Initialize character translation and type tables.
*/
static {
for (int i = 0; i < 256; i++) {
toUpper[i] = (byte)i;
toLower[i] = (byte)i;
}
for (int lc = "a"; lc <= "z"; lc++) {
int uc = lc + "A" - "a";
toUpper[lc] = (byte)uc;
toLower[uc] = (byte)lc;
isAlpha[lc] = true;
isAlpha[uc] = true;
isLower[lc] = true;
isUpper[uc] = true;
}
isWhite[ " "] = true;
isWhite["\t"] = true;
isWhite["\r"] = true;
isWhite["\n"] = true;
isWhite["\f"] = true;
isWhite["\b"] = true;
for (int d = "0"; d <= "9"; d++) {
isDigit[d] = true;
}
}
/**
* Returns the upper case equivalent of the specified ASCII character.
*/
public static int toUpper(int c) {
return toUpper[c & 0xff] & 0xff;
}
/**
* Returns the lower case equivalent of the specified ASCII character.
*/
public static int toLower(int c) {
return toLower[c & 0xff] & 0xff;
}
/**
* Returns true if the specified ASCII character is upper or lower case.
*/
public static boolean isAlpha(int c) {
return isAlpha[c & 0xff];
}
/**
* Returns true if the specified ASCII character is upper case.
*/
public static boolean isUpper(int c) {
return isUpper[c & 0xff];
}
/**
* Returns true if the specified ASCII character is lower case.
*/
public static boolean isLower(int c) {
return isLower[c & 0xff];
}
/**
* Returns true if the specified ASCII character is white space.
*/
public static boolean isWhite(int c) {
return isWhite[c & 0xff];
}
/**
* Returns true if the specified ASCII character is a digit.
*/
public static boolean isDigit(int c) {
return isDigit[c & 0xff];
}
/**
* Parses an unsigned integer from the specified subarray of bytes.
* @param b the bytes to parse
* @param off the start offset of the bytes
* @param len the length of the bytes
* @exception NumberFormatException if the integer format was invalid
*/
public static int parseInt(byte[] b, int off, int len)
throws NumberFormatException
{
int c;
if (b == null || len <= 0 || !isDigit(c = b[off++])) {
throw new NumberFormatException();
}
int n = c - "0";
while (--len > 0) {
if (!isDigit(c = b[off++])) {
throw new NumberFormatException();
}
n = n * 10 + c - "0";
}
return n;
}
public static int parseInt(char[] b, int off, int len)
throws NumberFormatException
{
int c;
if (b == null || len <= 0 || !isDigit(c = b[off++])) {
throw new NumberFormatException();
}
int n = c - "0";
while (--len > 0) {
if (!isDigit(c = b[off++])) {
throw new NumberFormatException();
}
n = n * 10 + c - "0";
}
return n;
}
/**
* Parses an unsigned long from the specified subarray of bytes.
* @param b the bytes to parse
* @param off the start offset of the bytes
* @param len the length of the bytes
* @exception NumberFormatException if the long format was invalid
*/
public static long parseLong(byte[] b, int off, int len)
throws NumberFormatException
{
int c;
if (b == null || len <= 0 || !isDigit(c = b[off++])) {
throw new NumberFormatException();
}
long n = c - "0";
long m;
while (--len > 0) {
if (!isDigit(c = b[off++])) {
throw new NumberFormatException();
}
m = n * 10 + c - "0";
if (m < n) {
// Overflow
throw new NumberFormatException();
} else {
n = m;
}
}
return n;
}
public static long parseLong(char[] b, int off, int len)
throws NumberFormatException
{
int c;
if (b == null || len <= 0 || !isDigit(c = b[off++])) {
throw new NumberFormatException();
}
long n = c - "0";
long m;
while (--len > 0) {
if (!isDigit(c = b[off++])) {
throw new NumberFormatException();
}
m = n * 10 + c - "0";
if (m < n) {
// Overflow
throw new NumberFormatException();
} else {
n = m;
}
}
return n;
}
}
Assign int value to char variable
public class MainClass {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = "Y";
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
ch1 and ch2: X Y
Character: is Lower Case
public class MainClass {
public static void main(String[] args) {
char symbol = "A";
if (Character.isLowerCase(symbol)) {
System.out.println("true");
}else{
System.out.println("false");
}
}
}
false
Character: is Upper Case
public class MainClass {
public static void main(String[] args) {
char symbol = "A";
if (Character.isUpperCase(symbol)) {
System.out.println("true");
}else{
System.out.println("false");
}
}
}
true
char variables behave like integers
public class MainClass {
public static void main(String args[]) {
char ch1;
ch1 = "X";
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
ch1 contains X ch1 is now Y
Checks if the string contains only ASCII printable characters.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class Main {
/**
* Checks if the string contains only ASCII printable characters.
*
* <code>null</code> will return <code>false</code>.
* An empty String ("") will return <code>true</code>.
*
* <pre>
* StringUtils.isAsciiPrintable(null) = false
* StringUtils.isAsciiPrintable("") = true
* StringUtils.isAsciiPrintable(" ") = true
* StringUtils.isAsciiPrintable("Ceki") = true
* StringUtils.isAsciiPrintable("ab2c") = true
* StringUtils.isAsciiPrintable("!ab-c~") = true
* StringUtils.isAsciiPrintable("\u0020") = true
* StringUtils.isAsciiPrintable("\u0021") = true
* StringUtils.isAsciiPrintable("\u007e") = true
* StringUtils.isAsciiPrintable("\u007f") = false
* StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
* </pre>
*
* @param str the string to check, may be null
* @return <code>true</code> if every character is in the range
* 32 thru 126
* @since 2.1
*/
public static boolean isAsciiPrintable(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (isAsciiPrintable(str.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* Checks whether the character is ASCII 7 bit printable.
*
* <pre>
* CharUtils.isAsciiPrintable("a") = true
* CharUtils.isAsciiPrintable("A") = true
* CharUtils.isAsciiPrintable("3") = true
* CharUtils.isAsciiPrintable("-") = true
* CharUtils.isAsciiPrintable("\n") = false
* CharUtils.isAsciiPrintable("©") = false
* </pre>
*
* @param ch the character to check
* @return true if between 32 and 126 inclusive
*/
public static boolean isAsciiPrintable(char ch) {
return ch >= 32 && ch < 127;
}
}
Checks whether the character is ASCII 7 bit.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
//--------------------------------------------------------------------------
/**
* Checks whether the character is ASCII 7 bit.
*
* <pre>
* CharUtils.isAscii("a") = true
* CharUtils.isAscii("A") = true
* CharUtils.isAscii("3") = true
* CharUtils.isAscii("-") = true
* CharUtils.isAscii("\n") = true
* CharUtils.isAscii("©") = false
* </pre>
*
* @param ch the character to check
* @return true if less than 128
*/
public static boolean isAscii(char ch) {
return ch < 128;
}
}
Checks whether the character is ASCII 7 bit alphabetic.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
/**
* Checks whether the character is ASCII 7 bit alphabetic.
*
* <pre>
* CharUtils.isAsciiAlpha("a") = true
* CharUtils.isAsciiAlpha("A") = true
* CharUtils.isAsciiAlpha("3") = false
* CharUtils.isAsciiAlpha("-") = false
* CharUtils.isAsciiAlpha("\n") = false
* CharUtils.isAsciiAlpha("©") = false
* </pre>
*
* @param ch the character to check
* @return true if between 65 and 90 or 97 and 122 inclusive
*/
public static boolean isAsciiAlpha(char ch) {
return (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z");
}
}
Checks whether the character is ASCII 7 bit alphabetic lower case.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
/**
* Checks whether the character is ASCII 7 bit alphabetic lower case.
*
* <pre>
* CharUtils.isAsciiAlphaLower("a") = true
* CharUtils.isAsciiAlphaLower("A") = false
* CharUtils.isAsciiAlphaLower("3") = false
* CharUtils.isAsciiAlphaLower("-") = false
* CharUtils.isAsciiAlphaLower("\n") = false
* CharUtils.isAsciiAlphaLower("©") = false
* </pre>
*
* @param ch the character to check
* @return true if between 97 and 122 inclusive
*/
public static boolean isAsciiAlphaLower(char ch) {
return ch >= "a" && ch <= "z";
}
}
Checks whether the character is ASCII 7 bit alphabetic upper case.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
/**
* Checks whether the character is ASCII 7 bit alphabetic upper case.
*
* <pre>
* CharUtils.isAsciiAlphaUpper("a") = false
* CharUtils.isAsciiAlphaUpper("A") = true
* CharUtils.isAsciiAlphaUpper("3") = false
* CharUtils.isAsciiAlphaUpper("-") = false
* CharUtils.isAsciiAlphaUpper("\n") = false
* CharUtils.isAsciiAlphaUpper("©") = false
* </pre>
*
* @param ch the character to check
* @return true if between 65 and 90 inclusive
*/
public static boolean isAsciiAlphaUpper(char ch) {
return ch >= "A" && ch <= "Z";
}
}
Checks whether the character is ASCII 7 bit control.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
/**
* Checks whether the character is ASCII 7 bit control.
*
* <pre>
* CharUtils.isAsciiControl("a") = false
* CharUtils.isAsciiControl("A") = false
* CharUtils.isAsciiControl("3") = false
* CharUtils.isAsciiControl("-") = false
* CharUtils.isAsciiControl("\n") = true
* CharUtils.isAsciiControl("©") = false
* </pre>
*
* @param ch the character to check
* @return true if less than 32 or equals 127
*/
public static boolean isAsciiControl(char ch) {
return ch < 32 || ch == 127;
}
}
Checks whether the character is ASCII 7 bit numeric.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
/**
* Checks whether the character is ASCII 7 bit numeric.
*
* <pre>
* CharUtils.isAsciiNumeric("a") = false
* CharUtils.isAsciiNumeric("A") = false
* CharUtils.isAsciiNumeric("3") = true
* CharUtils.isAsciiNumeric("-") = false
* CharUtils.isAsciiNumeric("\n") = false
* CharUtils.isAsciiNumeric("©") = false
* </pre>
*
* @param ch the character to check
* @return true if between 48 and 57 inclusive
*/
public static boolean isAsciiNumeric(char ch) {
return ch >= "0" && ch <= "9";
}
}
Checks whether the character is ASCII 7 bit numeric and character.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
/**
* Checks whether the character is ASCII 7 bit numeric and character.
*
* <pre>
* CharUtils.isAsciiAlphanumeric("a") = true
* CharUtils.isAsciiAlphanumeric("A") = true
* CharUtils.isAsciiAlphanumeric("3") = true
* CharUtils.isAsciiAlphanumeric("-") = false
* CharUtils.isAsciiAlphanumeric("\n") = false
* CharUtils.isAsciiAlphanumeric("©") = false
* </pre>
*
* @param ch the character to check
* @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
*/
public static boolean isAsciiAlphanumeric(char ch) {
return (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z") || (ch >= "0" && ch <= "9");
}
}
Checks whether the character is ASCII 7 bit printable.
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on char primitives and Character objects.
*
* This class tries to handle <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.
*
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class Main {
/**
* Checks whether the character is ASCII 7 bit printable.
*
* <pre>
* CharUtils.isAsciiPrintable("a") = true
* CharUtils.isAsciiPrintable("A") = true
* CharUtils.isAsciiPrintable("3") = true
* CharUtils.isAsciiPrintable("-") = true
* CharUtils.isAsciiPrintable("\n") = false
* CharUtils.isAsciiPrintable("©") = false
* </pre>
*
* @param ch the character to check
* @return true if between 32 and 126 inclusive
*/
public static boolean isAsciiPrintable(char ch) {
return ch >= 32 && ch < 127;
}
}
Compare Two Java char Arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
char[] a1 = new char[] { "a", "b", "c", "d" };
char[] a2 = new char[] { "a", "b", "c", "d" };
System.out.println(Arrays.equals(a1, a2));
}
}
compare two objects of Character
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class CharacterDemo {
public static void main(String args[]) {
Character a = new Character("a");
Character a2 = new Character("a");
Character b = new Character("b");
int difference = a.rupareTo(b);
if (difference == 0) {
System.out.println("a is equal to b.");
} else if (difference < 0) {
System.out.println("a is less than b.");
} else if (difference > 0) {
System.out.println("a is greater than b.");
}
System.out.println("a is " + ((a.equals(a2)) ? "equal" : "not equal")
+ " to a2.");
System.out.println("The character " + a.toString() + " is "
+ (Character.isUpperCase(a.charValue()) ? "upper" : "lower") + "case.");
}
}
Convert character to digit with Character.digit
public class MainClass {
public static void main(String args[]) {
System.out.printf( "Convert character to digit: %s\n",
Character.digit( "2", 1 ) );
}
}
Convert from ASCII code to String
public class Main {
public static void main(String[] args) throws Exception {
int i = 64;
String aChar = new Character((char) i).toString();
}
}
Convert from integer to ASCII code (byte)
public class Main {
public static void main(String[] args) throws Exception {
char c = "A";
int i = (int) c; // i == 65 DECIMAL
}
}
Convert string to char array
public class Main {
public static void main(String[] args) {
String literal = "Examples";
char[] temp = literal.toCharArray();
for (int i = 0; i < temp.length; i++) {
System.out.print(temp[i]);
}
}
}
Copy char array to string
public class Main {
public static void main(String[] args) {
char[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
String text = String.valueOf(data);
System.out.println(text);
text = String.copyValueOf(data, 3, 5);
System.out.println(text);
}
}
Count letters in a String
public class Main {
public static void main(String[] args) {
String str = "12345";
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i)))
counter++;
}
System.out.println(counter + " letters.");
}
}
//0 letters.
Demonstrate several Is... methods.
class IsDemo {
public static void main(String args[]) {
char a[] = { "a", "b", "5", "?", "A", " " };
for (int i = 0; i < a.length; i++) {
if (Character.isDigit(a[i]))
System.out.println(a[i] + " is a digit.");
if (Character.isLetter(a[i]))
System.out.println(a[i] + " is a letter.");
if (Character.isWhitespace(a[i]))
System.out.println(a[i] + " is whitespace.");
if (Character.isUpperCase(a[i]))
System.out.println(a[i] + " is uppercase.");
if (Character.isLowerCase(a[i]))
System.out.println(a[i] + " is lowercase.");
}
}
}
Determines if the specified string is permissible as a Java identifier.
/*
* Copyright 2005 Joe Walker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Main {
/**
* Determines if the specified string is permissible as a Java identifier.
* Returns true if the string is non-null, non-zero length with a Java
* identifier start as the first character and Java identifier parts in all
* remaining characters.
* @param test the string to be tested.
* @return true if the string is a Java identifier, false otherwise.
* @see java.lang.Character#isJavaIdentifierPart(char)
* @see java.lang.Character#isJavaIdentifierStart(char)
*/
public static boolean isJavaIdentifier(String test)
{
if (test == null || test.length() == 0)
{
return false;
}
if (!Character.isJavaIdentifierStart(test.charAt(0)) && test.charAt(0) != "_")
{
return false;
}
for (int i = 1; i < test.length(); i++)
{
if (!Character.isJavaIdentifierPart(test.charAt(i)) && test.charAt(i) != "_")
{
return false;
}
}
return true;
}
}
Determining a Character"s Unicode Block
public class Main {
public static void main(String[] argv) throws Exception {
char ch = "\u5639";
Character.UnicodeBlock block = Character.UnicodeBlock.of(ch);
}
}
Determining If a String Is a Legal Java Identifier
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = isJavaIdentifier("my_var");
}
public static boolean isJavaIdentifier(String s) {
if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i = 1; i < s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
}
return true;
}
}
Display printable Characters
public class MainClass {
public static void main(String[] args) {
for (int i = 32; i < 127; i++) {
System.out.write(i);
// break line after every eight characters.
if (i % 8 == 7)
System.out.write("\n");
else
System.out.write("\t");
}
System.out.write("\n");
}
}
! " # $ % & " ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
Escape Sequence Characters
\t tab
\b backspace
\n newline
\r carriage return
\" single quote
\" double quote
\\ backslash
Is character a digit, letter, white space, lower case or upper case character
public class Main {
public static void main(String[] args) {
char a[] = { "a", "b", "5", "?", "A", " " };
for (int i = 0; i < a.length; i++) {
if (Character.isDigit(a[i]))
System.out.println(a[i] + "is a digit ");
if (Character.isLetter(a[i]))
System.out.println(a[i] + "is a letter ");
if (Character.isWhitespace(a[i]))
System.out.println(a[i] + "is a White Space ");
if (Character.isLowerCase(a[i]))
System.out.println(a[i] + "is a lower case ");
if (Character.isLowerCase(a[i]))
System.out.println(a[i] + "is a upper case ");
}
}
}
isDigit(): true if the argument is a digit (0 to 9), and false otherwise.
public class MainClass {
public static void main(String[] args) {
char symbol = "A";
if (Character.isDigit(symbol)) {
System.out.println("true");
}else{
System.out.println("false");
}
}
}
false
isLetterOrDigit(): true if the argument is a letter or a digit, and false otherwise.
public class MainClass {
public static void main(String[] args) {
char symbol = "A";
if (Character.isLetterOrDigit(symbol)) {
System.out.println("true");
}else{
System.out.println("false");
}
}
}
true
isLetter(): true if the argument is a letter, and false otherwise.
public class MainClass {
public static void main(String[] args) {
char symbol = "A";
if (Character.isLetter(symbol)) {
System.out.println("true");
}else{
System.out.println("false");
}
}
}
true
is White space
isWhitespace():true if the argument is whitespace.
which is any one of the following characters:
space (" "), tab ("\t"), newline ("\n"), carriage return ("\r"),form feed ("\f")
public class MainClass {
public static void main(String[] args) {
char symbol = "A";
if (Character.isWhitespace(symbol)) {
System.out.println("true");
}else{
System.out.println("false");
}
}
}
false
Java char: char is 16 bit type and used to represent Unicode characters. Range of char is 0 to
public class Main {
public static void main(String[] args) {
char ch1 = "a";
char ch2 = 65;
System.out.println("Value of char variable ch1 is :" + ch1);
System.out.println("Value of char variable ch2 is :" + ch2);
}
}
/*
Value of char variable ch1 is :a
Value of char variable ch2 is :A
*/
Max and Min values of datatype char
public class Main {
public static void main(String[] args) {
System.out.println((int) Character.MIN_VALUE);
System.out.println((int) Character.MAX_VALUE);
}
}
//0
//65535
Plus one to char variable
public class Main {
public static void main(String[] args) {
char a = "A";
char b = (char) (a + 1);
System.out.println(a + b);
System.out.println("a + b is " + a + b);
}
}
Store unicode in a char variable
public class Main {
public static void main(String[] args) {
int x = 75;
char y = (char) x;
char half = "\u00AB";
System.out.println("y is " + y + " and half is " + half);
}
}
Storing Characters
Variables of type char
- store a single character code.
- occupy 16 bits, or 2 bytes,
- all characters in Java are stored as Unicode.
public class MainClass{
public static void main(String[] arg){
char myCharacter = "X";
System.out.println(myCharacter);
}
}
X
Thansform an array of ASCII bytes to a string. the byte array should contains only values in.
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/**
* Various string manipulation methods that are more efficient then chaining
* string operations: all is done in the same buffer without creating a bunch of
* string objects.
*
* @author
*/
public class Main {
/**
* Thansform an array of ASCII bytes to a string. the byte array should contains
* only values in [0, 127].
*
* @param bytes The byte array to transform
* @return The resulting string
*/
public static String asciiBytesToString( byte[] bytes )
{
if ( (bytes == null) || (bytes.length == 0 ) )
{
return "";
}
char[] result = new char[bytes.length];
for ( int i = 0; i < bytes.length; i++ )
{
result[i] = (char)bytes[i];
}
return new String( result );
}
}
To extract Ascii codes from a String
public class Main {
public static void main(String[] args) throws Exception {
String test = "ABCD";
for (int i = 0; i < test.length(); ++i) {
char c = test.charAt(i);
System.out.println((int) c);
}
}
}
/*
65
66
67
68
*/
Utility methods for ASCII character checking.
/**
* Utility methods for ASCII character checking.
*/
public class ASCIIUtil {
/**
* Checks whether the supplied character is a letter or number.
*/
public static boolean isLetterOrNumber(int c) {
return isLetter(c) || isNumber(c);
}
/**
* Checks whether the supplied character is a letter.
*/
public static boolean isLetter(int c) {
return isUpperCaseLetter(c) || isLowerCaseLetter(c);
}
/**
* Checks whether the supplied character is an upper-case letter.
*/
public static boolean isUpperCaseLetter(int c) {
return (c >= 65 && c <= 90); // A - Z
}
/**
* Checks whether the supplied character is an lower-case letter.
*/
public static boolean isLowerCaseLetter(int c) {
return (c >= 97 && c <= 122); // a - z
}
/**
* Checks whether the supplied character is a number
*/
public static boolean isNumber(int c) {
return (c >= 48 && c <= 57); // 0 - 9
}
}
Validate if a String contains only numbers
public class Main {
public static boolean containsOnlyNumbers(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i)))
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(containsOnlyNumbers("123456"));
System.out.println(containsOnlyNumbers("123abc456"));
}
}
/*
true
false
*/