Hi I want the opposite function of getNumericValue
int i = Character.getNumericValue('A');
if('A' == Character.someFunction(i)){
System.out.println("hooray");
}
I have tried "Character.forDigit" but this seems to be completely wrong.
Am new to java so please help.
The opposite is Character.forDigit
if(Character.forDigit(Character.getNumericValue('b'), Character.MAX_RADIX) == 'b') {
// true!
}
if(Character.forDigit(Character.getNumericValue('B'), Character.MAX_RADIX) == 'b') {
// true!
}
if(Character.getNumericValue('B') == Character.getNumericValue('b')) {
// true!
}
if((int)('B') == (int)'b') {
// false
}
Although given your question I think your looking for the actual ASCII char code for the letter.
Read this Java Character literals value with getNumericValue() post to see more information about Character.getNumericValue
To convert between char and int you can use typecasting. For example:
char myChar = (char) 65;
System.out.println(myChar);
will result in A. Hope that helps!
Character.getNumericValue('A') convert 'A' into unicode representation of the char. Probably you don't want to use that.
The letters A-Z in their uppercase ('\u0041' through '\u005A'),
lowercase ('\u0061' through '\u007A'), and full width variant
('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have
numeric values from 10 through 35. This is independent of the Unicode
specification, which does not assign numeric values to these char
values.
Related
What could be an efficient way to check a character is alphabet or not?
Using
Character.isLetter(ch)
(or)
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
Checking for A-Z a-z does not check all alphabetic characters. so the question seems moot.
Character.isAlphabetic(c) tests whether c is alphabetic.
Character.isLetter(c) tests whether c is a letter.
The two are not equivalent so you should be clear on the question you're trying to answer. The difference is that there are number-indications that are alphabetic but not letters; think Roman numerals. Link to list.
//function to check whether given character is an alphabet or not
function check(n){
var a=(+n); //If unary operator operates on a string then we get NaN.
if(isNaN(a)){ //Checking if a is NaN
console.log("This is a alphabet")
}
else{
console.log("Is a number")
}
}
check(12)
check("a");
In JAVA (Android), I'm trying to determine in a String, if each character has a equivalent in upper or lower case.
My goal is not to lower or upper the case, but to know if it's possible.
For example this function would return true for : 'e' 'é' 'i' 'l' 'L' 'O' 'P'
and false for emojis or chinese characters.
Is there any function that can do this?
EDIT : To be more clear, the function was supposed to take a character for argument, not a String and return false if the character had no uppercase or lowercase version.
You can try this:
boolean validate(char c){
return Character.isUpperCase(c) || Character.isLowerCase(c);
}
This will return true iff it is a Letter in uppercase or lower case only. Otherwise it'll return false.
The requirements are still not entirely specified (do you care whether the upper/lowercase equivalent is a different character from the original?), but my most straightforward interpretation of the question is:
For each character ch in a given string, is it true that either toUpperCase(ch) yields an uppercase character, or that toLowerCase(ch) yields a lowercase character?
I phrase it that way because Character.toUpperCase() returns "the uppercase equivalent of the character, if any; otherwise, the character itself".
The doc for String.toUppercase() doesn't mention what happens if there is no uppercase equivalent for some characters, but I think we can assume it returns those characters unchanged, as does Character.toUpperCase().
So a straightforward implementation of that condition would be to test
Character.isUpperCase(s.toUpperCase().charAt(0)) ||
Character.isLowerCase(s.toLowerCase().charAt(0));
for each character as a String.
I'm using the String rather than Character case conversion functions here, in order to take advantage of locale-sensitive mapping. Not only that, but regardless of locale, there are characters that cannot be converted to uppercase by Character.toUpperCase() because their uppercase equivalent is more than one character! For example, we would get incorrect results for \u00df 'ß' (see docs for details).
public class TestUpper {
public static void main(String[] args) {
final String test = "\u0633\u0644\u0627\u0645 World \u00df\u01c8eéilLOP\u76f4!";
for (Character ch : test.toCharArray()) {
System.out.format("'%c' (U+%04x): hasCase()=%b%n", ch, (int)ch, hasCase(ch));
}
}
static boolean hasCase(Character ch) {
String s = ch.toString();
// Does the character s have an uppercase or a lowercase equivalent?
return Character.isUpperCase(s.toUpperCase().charAt(0)) ||
Character.isLowerCase(s.toLowerCase().charAt(0));
}
}
And the results:
'س' (U+0633): hasCase()=false
'ل' (U+0644): hasCase()=false
'ا' (U+0627): hasCase()=false
'م' (U+0645): hasCase()=false
' ' (U+0020): hasCase()=false
'W' (U+0057): hasCase()=true
'o' (U+006f): hasCase()=true
'r' (U+0072): hasCase()=true
'l' (U+006c): hasCase()=true
'd' (U+0064): hasCase()=true
' ' (U+0020): hasCase()=false
'ß' (U+00df): hasCase()=true
'Lj' (U+01c8): hasCase()=true
'e' (U+0065): hasCase()=true
'é' (U+00e9): hasCase()=true
'i' (U+0069): hasCase()=true
'l' (U+006c): hasCase()=true
'L' (U+004c): hasCase()=true
'O' (U+004f): hasCase()=true
'P' (U+0050): hasCase()=true
'直' (U+76f4): hasCase()=false
'!' (U+0021): hasCase()=false
These test cases include Arabic letters and a Chinese character (which are isLetter(), but have no upper/lowercase equivalents), the requested test letters, space and punctuation, and a titlecase letter.
The results are correct according to the criteria currently stated in the question. However, the OP has said in comments that he wants the function to return false for titlecase characters, such as U+01c8, whereas the above code returns true because they have uppercase and lowercase equivalents (U+01c7 and U+01c9). But the OP's statement seems to be based on the mistaken impression that titlecase letters do not have uppercase and lowercase equivalents. Ongoing discussion has not yet resolved the confusion.
Disclaimer: This answer doesn't attempt to take into account supplementary or surrogate code points.
For a simple method, there's Character.isLowerCase. But you actually need to be careful- it depends on language. Some languages may have a lower case 'é' but no uppercase. Or like the turkish "I" may have a different lower case version than other languages.
To work around that, I'd use something like Character.isLetter(myChar) && String.valueOf(myChar).toLowerCase().equals(String.valueOf(myChar)). Remember to use the version of toLowerCase that takes a Locale as parameter if not comparing in the default Locale.
Check if the character is either a lowercase letter or an uppercase letter:
Character.isLowerCase(ch) != Character.isUpperCase(ch)
Alternatively, you can compare the lower and uppercased forms of the character:
Character.toLowerCase(ch) == Character.toUpperCase(ch)
However, you need to be careful about locale (there is one letter in Turkish where I think the lower and uppercase forms are the same).
Two strings uppercase and lowercase not matching does not necessarily mean the string is valid. true1 will not equal TRUE1 but fails the test case. You need to check each individual character. This is a rough cut, you'll probably have to do something fancy for emojis and Chinese characters.
public static boolean isAllCase(String value) {
String upper = value.toUpperCase();
String lower = value.toLowerCase();
if(upper.length() != lower.length())
return false;
for(int i = 0; i < upper.length(); i++) {
if(upper.charAt(i) == lower.charAt(i))
return false;
}
return true;
}
public boolean hasEquivalentCase(char ch) {
return (Character.isLowerCase(ch)) || Character.isUpperCase(ch)
}
public boolean validate(char value){
if( (value >= 'a' && value <= 'z') || (value >= 'A' &&
value <= 'Z')
return true;
return false;
}
this for each caracter to your String.
public boolean All( String cad ){
for( int i = 0; i < cad.lenght() ; i++ ){
if( !validate(cad.charAt(i)) ){
#the letter has not upper or lower
return false;
}
}
return true;
}
I'm looking for a straightforward answer and can't seem to find one.
I'm just trying to see if the following is valid. I want to take the integer 7 and turn it into the character '7'. Is this allowed:
int digit = 7;
char code = (char) digit;
Thank you in advance for your help!
This conversion is allowed, but the result won't be what you expect, because char 7 is the bell character whereas '7' is 55 (0x37). Because the numeric characters are in order, starting with '0' at 48 (0x30), just add '0', then cast the result as a char.
char code = (char) (digit + '0');
You may also take a look at the Unicode characters, of which the printable ASCII characters are the same codes.
'7' is Unicode code point U+0037.
Since it is a code point in the Basic Multiligual Plane, and since char is a UTF-16 code unit and that there is a one-to-one mapping between Unicode code points in this plane and UTF-16 code units, you can rely on this:
(char) ('0' + digit)
Do NOT think of '7' as ASCII 55 because that prevents a good understanding of char... For more details, see here.
Nope. The char '7' can be retrieved from int 7 in these ways:
int digit = 7;
char code = Integer.toString(digit).charAt(0);
code = Character.forDigit(digit, 10);
If digit is between 0 and 9:
int digit = 7;
char code = (char)(((int)'0')+digit);
So I just started reading "Java In A Nutshell", and on Chapter One it states that:
"To include a character literal in a Java program, simply place it between single quotes"
i.e.
char c = 'A';
What exactly does this do^? I thought char only took in values 0 - 65,535. I don't understand how you can assign 'A' to it?
You can also assign 'B' to an int?
int a = 'B'
The output for 'a' is 66. Where/why would you use the above^ operation?
I apologise if this is a stupid question.
My whole life has been a lie.
char is actually an integer type. It stores the 16-bit Unicode integer value of the character in question.
You can look at something like http://asciitable.com to see the different values for different characters.
In Java char literals represent UTF-16 (character encoding schema) code units. What you got from UTF-16 is mapping between integer values (and the way they are saved in memory) with corresponding character (graphical representation of unit code).
You can enclose characters in single quotes - this way you don't need to remember UTF-16 values for characters you use. You can still get the integer value from character type and put if for example in int type (but generally not in short, they both use 16 bits but short values are from -32768 to 32767 and char values are from 0 to 65535 or so).
If you look at an ASCII chart, the character "A" has a value of 41 hex or 65 decimal. Using the ' character to bracket a single character makes it a character literal. Using the double-quote (") would make it a String literal.
Assigning char someChar = 'A'; is exactly the same as saying char someChar = 65;.
As to why, consider if you simply want to see if a String contains a decimal number (and you don't have a convenient function to do this). You could use something like:
bool isDecimal = true;
for (int i = 0; i < decString.length(); i++) {
char theChar = decString.charAt(i);
if (theChar < '0' || theChar > '9') {
isDecimal = false;
break;
}
}
I want to check a char variable is one of 21 specific chars, what is the shortest way I can do this?
For example:
if(symbol == ('A'|'B'|'C')){}
Doesn't seem to be working. Do I need to write it like:
if(symbol == 'A' || symbol == 'B' etc.)
If your input is a character and the characters you are checking against are mostly consecutive you could try this:
if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
// ...
}
However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:
if (symbol.matches("[A-Z?]")) {
// ...
}
If you have a character you'll first need to convert it to a string before you can use a regular expression:
if (Character.toString(symbol).matches("[A-Z?]")) {
// ...
}
If you know all your 21 characters in advance you can write them all as one String and then check it like this:
char wanted = 'x';
String candidates = "abcdefghij...";
boolean hit = candidates.indexOf(wanted) >= 0;
I think this is the shortest way.
The first statement you have is probably not what you want... 'A'|'B'|'C' is actually doing bitwise operation :)
Your second statement is correct, but you will have 21 ORs.
If the 21 characters are "consecutive" the above solutions is fine.
If not you can pre-compute a hash set of valid characters and do something like
if (validCharHashSet.contains(symbol))...
you can use this:
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(String.valueOf(yourChar)))
note that you do not need to create a separate String with the letters A-Z.
It might be clearer written as a switch statement with fall through e.g.
switch (symbol){
case 'A':
case 'B':
// Do stuff
break;
default:
}
If you have specific chars should be:
Collection<Character> specificChars = Arrays.asList('A', 'D', 'E'); // more chars
char symbol = 'Y';
System.out.println(specificChars.contains(symbol)); // false
symbol = 'A';
System.out.println(specificChars.contains(symbol)); // true
Using Guava:
if (CharMatcher.anyOf("ABC...").matches(symbol)) { ... }
Or if many of those characters are a range, such as "A" to "U" but some aren't:
CharMatcher.inRange('A', 'U').or(CharMatcher.anyOf("1379"))
You can also declare this as a static final field so the matcher doesn't have to be created each time.
private static final CharMatcher MATCHER = CharMatcher.anyOf("ABC...");
Option 2 will work. You could also use a Set<Character> or
char[] myCharSet = new char[] {'A', 'B', 'C', ...};
Arrays.sort(myCharSet);
if (Arrays.binarySearch(myCharSet, symbol) >= 0) { ... }
You can solve this easily by using the String.indexOf(char) method which returns -1 if the char is not in the String.
String candidates = "ABCDEFGHIJK";
if(candidates.indexOf(symbol) != -1){
//character in list of candidates
}
Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.
Alternatively you could put your valid values into an array and check for the existence of symbol in the array.
pseudocode as I haven't got a java sdk on me:
Char candidates = new Char[] { 'A', 'B', ... 'G' };
foreach(Char c in candidates)
{
if (symbol == c) { return true; }
}
return false;
One way to do it using a List<Character> constructed using overloaded convenience factory methods in java9 is as :
if(List.of('A','B','C','D','E').contains(symbol) {
// do something
}
You can just write your chars as Strings and use the equals method.
For Example:
String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";
if (firstChar.equalsIgnoreCase(secondChar) ||
(firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
System.out.println(firstChar + " is the same as " + secondChar);
} else {
System.out.println(firstChar + " is different than " + secondChar);
}