Formatting numbers with same amount of padding - java

I want to format 3 digit floats in Java so they line up vertically such that they look like:
123.45
99
23.2
45
When I use DecimalFormat class, I get close, but I want to insert spaces when the item has 1 or 2 digits.
My code:
DecimalFormat formatter = new java.text.DecimalFormat("####.##");
float [] floats = [123.45, 99.0, 23.2, 45.0];
for(int i=0; i<floats.length; i++)
{
float value = floats[i];
println(formatter.format(value));
}
It produces:
123.45
99
23.2
45
How can I print it so that all but the first line is shifted over by 1 space?

Try with String.format() (JavaDoc):
public static void main(String args[]){
String format = "%10.2f\n"; // width == 10 and 2 digits after the dot
float [] floats = {123.45f, 99.0f, 23.2f, 45.0f};
for(int i=0; i<floats.length; i++) {
float value = floats[i];
System.out.format(format, value);
}
and the output is :
123.45
99.00
23.20
45.00

This is trivial with a bit of regular expression string replacement.
formatter.format(f).replaceAll("\\G0", " ")
Here it is in context: (see also on ideone.com):
DecimalFormat formatter = new java.text.DecimalFormat("0000.##");
float[] floats = {
123.45f, // 123.45
99.0f, // 99
23.2f, // 23.2
12.345f, // 12.35
.1234f, // .12
010.001f, // 10
};
for(float f : floats) {
String s = formatter.format(f).replaceAll("\\G0", " ");
System.out.println(s);
}
This uses DecimalFormat to do most of the formatting (the zero padding, the optional #, etc) and then uses String.replaceAll(String regex, String replacement) to replace all leading zeroes to spaces.
The regex pattern is \G0. That is, 0 that is preceded by \G, which is the "end of previous match" anchor. The \G is also present at the beginning of the string, and this is what allows leading zeroes (and no other zeroes) to be matched and replaced with spaces.
References
java.util.regex.Pattern
regular-expressions.info - Continuing Matches
On escape sequences
The reason why the pattern \G0 is written as "\\G0" as a Java string literal is because the backslash is an escape character. That is, "\\" is a string of length one, containing the backslash.
References
JLS 3.10.6 Escape Sequences for Character and String Literals
Related questions
How to replace a special character with single slash
Is the char literal '\"' the same as '"' ?(backslash-doublequote vs only-doublequote)
Additional tips
Note that I've used the for-each loop, which results in a much simpler code, thus enhancing readability and minimizing chances of mistakes. I've also kept the floating point variables as float, using the f suffix to declare them as float literals (since they're double by default otherwise), but it needs to be said that generally you should prefer double to float.
See also
Java Language Guide/For-each loop
Java Puzzlers: Prefer double to float.

Just change your first line, replacing '#' characters by '0'. It will solve your problem and produce formatted numbers with the same length, as explicated in the Java API. With that method, your lines will start and end with additional '0' numbers (099.00 for example) :
DecimalFormat formatter = new java.text.DecimalFormat("0000.00");
If you want a correct alignment without theses useless '0', you'll have to create your own formatting method : it doesn't exist in the native Java API.

In the same vein as Benoit's answer, here's a class extending DecimalFormat which ensures a specified minimum length by left-padding formatted numbers with spaces. It's tested (Java 6, 7), more general and provides a working example.
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.FieldPosition;
public class PaddingDecimalFormat extends DecimalFormat {
private int minimumLength;
/**
* Creates a PaddingDecimalFormat using the given pattern and minimum minimumLength and the symbols for the default locale.
*/
public PaddingDecimalFormat(String pattern, int minLength) {
super(pattern);
minimumLength = minLength;
}
/**
* Creates a PaddingDecimalFormat using the given pattern, symbols and minimum minimumLength.
*/
public PaddingDecimalFormat(String pattern, DecimalFormatSymbols symbols, int minLength) {
super(pattern, symbols);
minimumLength = minLength;
}
#Override
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
int initLength = toAppendTo.length();
super.format(number, toAppendTo, pos);
return pad(toAppendTo, initLength);
}
#Override
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
int initLength = toAppendTo.length();
super.format(number, toAppendTo, pos);
return pad(toAppendTo, initLength);
}
private StringBuffer pad(StringBuffer toAppendTo, int initLength) {
int numLength = toAppendTo.length() - initLength;
int padLength = minimumLength - numLength;
if (padLength > 0) {
StringBuffer pad = new StringBuffer(padLength);
for(int i = 0; i < padLength; i++) {
pad.append(' ');
}
toAppendTo.insert(initLength, pad);
}
return toAppendTo;
}
public static void main(String[] args) {
PaddingDecimalFormat intFormat = new PaddingDecimalFormat("#", 6);
for (int i = 0; i < 20; i++) {
System.out.println(intFormat.format(i) + intFormat.format(i*i*i));
}
}
}

A method that should answer your problem (I wrote it directly here and did not tested it so you could have some bugs to correct, but at least, you get the idea) :
public class PaddingDecimalFormat extends DecimalFormat {
private int maxIntLength = 1;
public PaddingDecimalFormat(String pattern) {
super(pattern);
}
public void configure(Number[] numbers) {
for(Number number : numbers) {
maxIntLength = Math.max(maxIntLength, Integer.toString(number.intValue()).length());
}
}
#Override
public void format(Number number) {
int padding = maxIntLength - Integer.toString(number.intValue()).length();
StringBuilder sb = new StringBuilder();
for(int i=0; i<padding; i++) {
sb.append(' ');
}
sb.append(super.format(number));
return sb.toString();
}
}

Imagine semicolon and System.out.; formatter like above in question.
printf (" ".substring (("" + Math.round (f)).length ) + formatter.format (f))
I would prefer a log-10-Function, to calculate the size of 999 or 100 to 3, instead of the implicit toString-call, but I just find logarithm naturalis.
Math.round (987.65) gives 987.
("" + 987).length gives 3
"___".substring (3) is the empty string, for a short number (0-9) it will return two blanks.

Related

How to delete every 12th character from a string in java

Lets say I have a string like this:
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa"
int character = 12
What I want to do is delete every 12th character in the string, so i would delete the 12 index, then the 24th, then the 36th, etc until the string is over.
Which index I delete (every 12th, or every 2nd) has to equal the character variable I have, since that variable changes.
I tried doing this with regex:
System.out.println(s.replaceAll(".(.)", "$12"));
But it didnt work. any help?
Sometimes, a simple for loop is all you need:
public class Test {
public static void main(String[] args) {
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
int character = 12;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if ((i + 1) % character != 0) {
sb.append(str.charAt(i));
}
}
String result = sb.toString();
System.out.println(result);
}
}
If you insist on using regular expressions, you can interpolate the character variable into the expression as follows:
public class Test {
public static void main(String[] args) {
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
int character = 12;
System.out.println(str.replaceAll("(.{" + (character - 1) + "}).", "$1"));
}
}
To delete every 12th character using regex, use this pattern:
(.{11}).
And then replace with just the captured $1.
Sample Java code:
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
String output = str.replaceAll("(.{11}).", "$1");
System.out.println(output);
This prints:
~asdfl;kjx,rgadfaeg,dsfnewgfljka;dfjsfa;dlkja;lvjvbnabe;fwelfjadfaa
Edit:
To do a regex replacement of some fixed width, use:
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
int width = 11;
String output = str.replaceAll("(.{" + width + "}).", "$1");
System.out.println(output);
Avoid char
The char type in Java is legacy, essentially broken. As a 16-bit value, a char is incapable of representing most characters.
Code points
Instead, use code point integers.
Make an array of each character’s code point.
int[] codePointsArray = input.codePoints().toArray() ;
Make a list of that array.
List< Integer > codePoints = List.of( codePointsArray ) ;
Alternatively:
List< Integer > codePoints = input.codePoints().boxed().toList() ;
Make an IntStream of the indexes we need to access each element of that list. Use each index to pull out a code point, and filter by the nth element. Collect into a StringBuilder.
String result =
IntStream
.range( 0 , codePoints.size() )
.filter( n -> n % 12 != 0 )
.mapToObj( codePoints :: get )
.collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append )
.toString()
;
That is untested code, but should be close to what you need.
My code here is based on what I saw on this similar Question.

Number with group-separator and decimal-separator convert into decimal number

I want to convert the number "4,471.26" into decimal number "4471.26".
Actually number "4,471.26" is received as String and for further process, need to convert it into Decimal number.
"4,471.26" - is just a format,so value is keeps changing every-time. This value could be anything like "654,654,25.54"
Tried by considering comma (,) as group -separator. But looks like has different ASCII values.
String Tempholder = "4,471.26";
Decimal.valueOf(Tempholder.replaceAll(getGroupSeparator(), ""));
private char getGroupSeparator() {
DecimalFormat decFormat = new DecimalFormat();
DecimalFormatSymbols decSymbols = decFormat.getDecimalFormatSymbols();
return Character.valueOf(decSymbols.getGroupingSeparator());
}
Below code would be temporary solution, but it will not work other geo regions.
String Tempholder = "4,471.26";
Decimal.valueOf(Tempholder.replaceAll(",", ""));
Kindly help ..
you can do it like this :
public class JavaCodes{
public static void main(String[] args) {
String str = new String("4,233.19");
str = str.replaceFirst(",", "");
System.out.println(Double.valueOf(str));
}
}
Ok, some assumptions first
You don't know the locale beforehand
If just one separator is found, and it appears only once, we treat it as a decimal separator (for simplicity)
If just one separator is found but it appears multiple times, it's a thousands separator
Any non-digit character is a valid separator
If there are more than two non-digit characters in a string, that's an error.
So here's the algorithm
Find the first non-digit character and temporarily consider it a decimal separator
If another non-digit character is found
If it's the same as the decimal separator, and we still don't have a thousands seprator, make that the thousands separator and reset the decimal separator
If it's the same as the decimal separator, and we already have a thousands separator, that's an error
If it's not the same as the decimal separator, it's the thousands separator
Remove from the original string all occurrences of the thousands separator (if present)
Substitute the decimal separator with a dot
Parse as double.
And here is the code.
public class Test {
public static double parseNumber(String x) {
Character thousandsSeparator = null;
Character decimalSeparator = null;
for (int i = 0; i < x.length(); i++) {
if (!Character.isDigit(x.charAt(i))) {
if (decimalSeparator == null) {
decimalSeparator = x.charAt(i);
} else {
if (decimalSeparator.equals(x.charAt(i))) {
if (thousandsSeparator == null) {
thousandsSeparator = x.charAt(i);
decimalSeparator = null;
} else {
if (!thousandsSeparator.equals(x.charAt(i))) {
throw new IllegalArgumentException();
}
}
} else {
thousandsSeparator = x.charAt(i);
}
}
}
}
// remove thousands separator
if (thousandsSeparator != null) {
int formerSeparatorPosition;
while ((formerSeparatorPosition = x.indexOf(thousandsSeparator)) != -1) {
x = x.substring(0, formerSeparatorPosition) + x.substring(formerSeparatorPosition + 1);
}
}
// replace decimal separator with a dot
if (decimalSeparator != null) {
x = x.replace(decimalSeparator, '.');
}
return Double.parseDouble(x);
}
public static void main(String args[]) {
System.out.println(parseNumber("123.45"));
System.out.println(parseNumber("123,45"));
System.out.println(parseNumber("1.234,5"));
System.out.println(parseNumber("1,234.5"));
System.out.println(parseNumber("1,234,567.512"));
System.out.println(parseNumber("1.234.567,512"));
ystem.out.println(parseNumber("1.234.567"));
System.out.println(parseNumber("1_234_567|34")); // works with any two characters, if there are just two
try {
System.out.println(parseNumber("1_234_567|34,7")); // invalid
} catch (IllegalArgumentException e) {
System.out.println("Too many separators!");
}
}
}
It is quite circumstantial to parse to a BigDecimal. To a double it is easier
but floating point is just an approximation, and will loose the number's precision. 0.2 == 0.20 == 0.200 == (actually something like) 0.1999999987.
String text = "4,471.26";
DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parseObject(text);
// number.scale() == 2
The US locale uses your desired separators.
Thank you guys, for all your suggestion and helps. I figure out the below solution. Convert it into decimal number, And applicable to all geo region.
public static void geoSp() {
String a = "4.233,19";
NumberFormat as = NumberFormat.getInstance();
double myNumber = 0;
try {
myNumber = as.parse(a).doubleValue();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(String.valueOf(myNumber));
}
gives Out put :- 4233.19

Converting hexadecimal to a char that has 3 digits

I have a problem converting hexadecimal to a character when the hexadecimal has 3 digits
I have 2 methods which escape and unescape characters over decimal value 127
test\\b8 is produced when test¸ is escaped
The unescape does the following:
for (int i=0, n=node.length; i<n; i++) {
if(c == "\\"){
char c2 = node[i + 1];
char c3 = node[i + 2];
int i= Integer.parseInt(str,16);
char c = (char)i;
System.out.println("Char is:=" + c);
}
}
output - test¸
As you can see I take the first two characters after the slash and convert them into a char. This all works fine. However there are sometimes characters that have 3 hexadecimal digits (for example test\\2d8. This should unescape as test˘). When this enters into my unescape method is won't use all 3 characters. Only the first 2 and therefore the produce wrong results.
Is there a way to determine when to convert 2 or 3 characters
Here's what I would do:
String raw = new String(node); // might be a better way to get a string from the chars
int slashPos = raw.indexOf('\\');
if(slashPos >= 0) {
String hex = raw.substring(slashPos + 1);
int value = Integer.parseInt(hex,16);
}
In this manner, we're not special casing anything for 2, 3, 4, or 100 digits (although I'm sure 100 digits would throw an exception :-) ). Instead, we're using the protocol as a 'milestone' in the string, and then just accepting that everything after the slash is the hex string.
class HexParse {
private static class HexResult {
final boolean exists;
final int value;
HexResult(boolean e, int v) { exists = e; value = v; }
}
private final String raw;
private final HexResult result;
public HexParse(String raw) {
this.raw = raw;
int slashPos = raw.indexOf('\\');
boolean noSlash = slashPos < 0;
boolean noTextAfterSlash = slashPos > raw.length() - 2;
if(noSlash || noTextAfterSlash) {
result = new HexResult(false,0);
} else {
// throws exception if second part of string contains non-hex chars
result = new HexResult(true,Integer.parseInt(raw.substring(slashPos + 1),16));
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(raw).append(" ");
if(result.exists) {
sb.append("has hex of decimal value ").append(result.value);
} else {
sb.append("has no hex");
}
return sb.toString();
}
public static void main(String...args) {
System.out.println(new HexParse("test`hello")); // none
System.out.println(new HexParse("haha\\abcdef")); // hex
System.out.println(new HexParse("good\\f00d")); // hex
System.out.println(new HexParse("\\84b")); // hex
System.out.println(new HexParse("\\")); // none
System.out.println(new HexParse("abcd\\efgh")); //exception
}
}
c:\files\j>javac HexParse.java
c:\files\j>java HexParse
test`hello has no hex
haha\abcdef has hex of decimal value 11259375
good\f00d has hex of decimal value 61453
\84b has hex of decimal value 2123
\ has no hex
Exception in thread "main" java.lang.NumberFormatException: For input string: "e
fgh"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at HexParse.<init>(HexParse.java:21)
at HexParse.main(HexParse.java:

DecimalFormat pattern problem

I try to format a number using NumberFormatter in Android. I use the code bellow and it works perfectly:
NumberFormat formatter = new DecimalFormat("###,###");
String myFormattedString = formatter.format(123456);
But, when i use a pattern with space, like that: new DecimalFormat("###,# ##"); it throws an IllegalArgumentException. I've read documentation about NumberFormatter and DecimalFormatter and found nothing about spaces in patterns. Can anyone explane me why can't i use spaces or how to add them as allowed characters.
Thanks in advance!!!
You can not put spaces in the middle of a number: it is not a valid format.
If you look at the JavaDoc of DecimalFormat, you'll see this:
Prefix:
any Unicode characters except \uFFFE, \uFFFF, and special characters
Suffix:
any Unicode characters except \uFFFE, \uFFFF, and special characters
Number:
Integer Exponentopt
Integer . Fraction Exponentopt
Without copying the entire doc, none of the components of the Number pattern accept spaces, so trying to fit a space in the middle will not work. You can only use spaces in the prefix or suffix.
In a regular JDK this does not throw an exception - it just formats the number as 123,456.
It is not clear what is the space in your example. You have a couple of options for a symbol's role:
decimal separator
group separator
exponent separator
monetary decimal separator
You can set each of these with:
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
formatter.setSymbols(symbols);
I've achieved my goal by making my own formatter using standart formatter and finding prohibited symbols using exeptions. Hope it will be useful for someone else.
public static String getFormattedNumberWithPattern(String aPattern,
float aNumber) {
String lFormattedNumber = null;
String lOriginalPattern = aPattern;
try {
Hashtable<Integer, String> lIlligalChars = new Hashtable<Integer, String>();
// analyze illegal characters
for (int i = aPattern.length() - 1; i >= 0; i--) {
char[] lAux = new char[1];
aPattern.getChars(i, i + 1, lAux, 0);
try {
// if character is illegal, it throws an exception
#SuppressWarnings("unused")
NumberFormat lNumberFormatter = new DecimalFormat("#"
+ lAux[0] + "#");
} catch (IllegalArgumentException e) {
// add illegal chars and indexes to dictionary
lIlligalChars.put(new Integer(i), String.valueOf(lAux[0]));}}
Enumeration<String> lChars = lIlligalChars.elements();
while (lChars.hasMoreElements()) {
String lIllegalChar = lChars.nextElement();
// remove illegal chars from pattern
aPattern = removeChar(aPattern, lIllegalChar.charAt(0));
}
// format number using legal pattern
NumberFormat lNumberFormatter = new DecimalFormat(aPattern);
lFormattedNumber = lNumberFormatter.format(aNumber);
int lLenghtDifference = lOriginalPattern.length()
- lFormattedNumber.length();
// add illegal chars to formatted string using their indexes
Enumeration<Integer> lKeys = lIlligalChars.keys();
while (lKeys.hasMoreElements()) {
Integer lIllegalCharIndex = lKeys.nextElement();
int lInsertIndex = lIllegalCharIndex.intValue()
- lLenghtDifference;
// insert illegal chars into formatted number
if (lInsertIndex >= 0
|| lInsertIndex < lFormattedNumber.length()) {
lFormattedNumber = new StringBuffer(lFormattedNumber)
.insert(lInsertIndex,
lIlligalChars.get(lIllegalCharIndex)
.charAt(0)).toString();
}
}
} catch (Exception e) {
// Log.d("info", "formater error:" + e + "mask: " + aPattern
// + " number:" + aNumber);
}
return lFormattedNumber;
}
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt(current++, cur);
}
r.setLength(current);
return r.toString();
}

How to check if a String contains only ASCII?

The call Character.isLetter(c) returns true if the character is a letter. But is there a way to quickly find if a String only contains the base characters of ASCII?
From Guava 19.0 onward, you may use:
boolean isAscii = CharMatcher.ascii().matchesAllOf(someString);
This uses the matchesAllOf(someString) method which relies on the factory method ascii() rather than the now deprecated ASCII singleton.
Here ASCII includes all ASCII characters including the non-printable characters lower than 0x20 (space) such as tabs, line-feed / return but also BEL with code 0x07 and DEL with code 0x7F.
This code incorrectly uses characters rather than code points, even if code points are indicated in the comments of earlier versions. Fortunately, the characters required to create code point with a value of U+010000 or over uses two surrogate characters with a value outside of the ASCII range. So the method still succeeds in testing for ASCII, even for strings containing emoji's.
For earlier Guava versions without the ascii() method you may write:
boolean isAscii = CharMatcher.ASCII.matchesAllOf(someString);
You can do it with 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
*/
}
}
Detect non-ASCII character in a String
Here is another way not depending on a library but using a regex.
You can use this single line:
text.matches("\\A\\p{ASCII}*\\z")
Whole example 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"));
}
}
Understanding the regex :
li \\A : Beginning of input
\\p{ASCII} : Any ASCII character
* : all repetitions
\\z : End of input
Iterate through the string and make sure all the characters have a value less than 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;
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}]", "");
}
In Java 8 and above, one can use String#codePoints in conjunction with IntStream#allMatch.
boolean allASCII = str.codePoints().allMatch(c -> c < 128);
In Kotlin:
fun String.isAsciiString() : Boolean =
this.toCharArray().none { it < ' ' || it > '~' }
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;
}
}
//return is uppercase or lowercase
public boolean isASCIILetter(char c) {
return (c > 64 && c < 91) || (c > 96 && c < 123);
}

Categories