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);
}
Related
i'm working on my project in java, in my project i need to get input from some stream an to parse text and make it to generic char-by-char to some other types, one of them is "ValueNumber".
for that I'm using switch case
Now,because Number can start with ' - ' I need to check if the current char is a Digit between 0 to 9 or ' - ' or something else.
My question is how can I make some variable that will hold all the 10th digits by one variable ?
String will hold it, or StringBuilder for better performance and
then you can parse the string and see if it matches the regex:
return str.matches("[-]?[0-9]+");
if true, it is digit with or without negation sign, if false, it is not a digit you described. The digit can be as long as String allows.
I think you're imagining something like:
switch(aChar) {
case '+':
handlePlus();
break;
case ' ':
handleSpace();
break;
case anyOf("-01234567890");
handlePartOfNumber(aChar);
break;
}
Unfortunately in Java, switch is not this sophisticated. switch deals with exact matches only.
You will need to use a series of if/else blocks instead:
if(aChar == '+') {
handlePlus();
} else if(aChar == ' ') {
handleSpace();
} else if(isMinusOrDigit(aChar)) {
handlePartOfNumber(aChar);
}
Now, how do we implement isMinusOrDigit(char c)?
You've asked about "some variable that holds all the digits". Maybe you mean an array, or a List or a Set. I'll choose Set because it's the purest "bag of items, you don't care the order".
private static Set<Character> MINUS_AND_DIGITS = minusAndDigits();
private static Set<Character> minusAndDigits() {
Set<Character> set = new HashSet<>();
for(char c = '0'; c<='9'; c++) {
set.add(c);
}
set.add('-');
}
private static boolean isMinusOrDigit(char c) {
return MINUS_AND_DIGITS.contains(c);
}
You could also use
a List<Character> (again .contains(c))
an array -- char[] (see How can I test if an array contains a certain value?)
or even a String -- return "0123456789-".indexOf(c) != -1;
But in this case, you don't need a "multi value variable" to work out whether a character is a minus or a digit - because the number characters are next to each other in ASCII:
private static boolean isMinusOrDigit(char c) {
return c == '-' || ( c >= 0 && c<=9 );
}
How find if the first three characters in a char[] seqarr are A/a, T/t, G/g in this order (case insensitive) in Java
I tried this
for(int i = 0; i <= 2; i++){
if(seqarr[i] == 'A'|| seqarr[i] == 'a' ||seqarr[i] == 'T' ||seqarr[i] == 't'|| seqarr[i] == 'G'|| seqarr[i] == 'g' ){
return true;
}
It is easier to work with a String, but unnecessary: you can simply work with the individual characters, uppercasing them to normalize for case:
return arr.length >= 3
&& Character.toUpperCase(arr[0]) == 'A'
&& Character.toUpperCase(arr[1]) == 'T'
&& Character.toUpperCase(arr[2]) == 'G';
This avoids creating any objects, so will likely be faster than converting to String.
You could also just be explicit about the upper and lower case variants:
(arr[0] == 'A' || arr[0] == 'a')
Instead of Character.toUpperCase etc. The downside of that is that it's easy to make a mistake in getting the correct upper/lowercase pairs when you copy and paste (as demonstrated in #Tim's comment below: A/t, rather than A/a).
This would be much easier to handle if you were working with strings instead of character arrays. The reason for this is that using your current approach you will need to check each of the three individual characters, three times, for each starting pattern. That being said, one way to approach this would be to convert the character array back to a string and do the check there:
public boolean isValid(char[] array) {
if (array.length < 3) {
return false;
}
// create string from only first 3 characters of array
String str = new String(array, 0, 3);
return str.equalsIgnoreCase("atg");
}
char[] array = {'A', 't', 'G', 'c', '/', 'C', 'G'}; // ... and more data
isValid(array);
This approach should perform well because it avoids creating a lengthy string from a character array. All we need are the first three characters in order to perform the check.
You can use a String instead of a char array and use indexOf method.
String s = new String(seqarr);
s = s.toLowerCase();
System.out.println(s.indexOf("atg") == 0);
You may use copyValueOf from String to convert the char array to String. Then use equalsIgnoreCase to compare.
public boolean isValid(char[] seqarr) {
return String.copyValueOf(seqarr, 0, 3).equalsIgnoreCase("atg");
}
If I got your question right, then you want to find if the first three characters are either ATG or not, in the right order, like
ATGsomething
aTGsomething
AtGsomething
Atgsomething
...
Then you can do this using regular expressions as well
String str = String.valueOf(seqarr);
if(str.matches("^[Aa][Tt][Gg]")) {
return true;
}
You can also do it by tweaking your code a little bit
if( seqarr.length>=3 && (seqarr[0] == 'A'|| seqarr[0] == 'a') && (seqarr[1] == 'T' ||seqarr[1] == 't') && (seqarr[2] == 'G'|| seqarr[2] == 'g' ){
return true;
I would make a simple code in java to replace the letter 'z' by letter 'y' >>> here are the code
String s= "generalization";
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='z') s.charAt(i)='y';
The compiler return to me an error >>> why?
Strings are immutable. You can use a simple character array and alter the characters at the corresponding indices
Something like this perhaps:
String s = "Generalization";
char[] sChars = s.toCharArray();
for (int i = 0; i < sChars.length; i++) {
if (sChars[i] == 'z') {
sChars[i] = 'y';
}
}
s = String.copyValueOf(sChars);
System.out.println(s);
Prints out: Generaliyation
Or like suggested in another answer, in this sort of cases there is something called Regular expressions aka regex, with this the same thing is also accomplished by writing:
String s = "Generalization";
s = s.replace("z", "y");
System.out.println(s);
This also prints out: Generaliyation.
You can use the method replaceAll of the String class.
String s = "generalization";
s = s.replaceAll("[z]", "y");
Be careful, the first argument is a regex!
So I have dealt with this problem before and thought there would be an accepted pattern to solve the problem, but I have yet to find anything. I tried searching around and I have tried tinkering around myself and neither resulted in any satisfactory answers so I am turning to SO
String str = "blah1blah2"
I want to know whether the char '1' or '2' occurs first (this is just a made up example obviously). I know I could use str.indexOf() for 1 and 2 to compare, but this presents the problem of it possibly returning -1.
Let me know what would be a good way to tackle this.
FYI: I am working in Java but I think this sort of indexOf function is pretty common in other languages.
I don't know what degree of flexibility you require, but I would just do this the good-old-fashioned way of looping through the String, something like this:
public static char findFirstChar(String str, char c1, char c2) {
for (char c : str.toCharArray())
if (c == c1 || c == c2)
return c;
return 0;
}
Of course, this will return the char it encounters first or 0 if neither neither chars are found in the string.
If you want to search for an arbitrary number of character:
public static char findFirstChar(String str, char ... chars) {
for (char c1 : str.toCharArray())
for (char c2 : chars)
if (c1 == c2)
return c1;
return 0;
}
I would say you should start by defining exactly what behavior you want. Assume your search terms are "1" and "2", what should be returned for each of the following strings?
"blah1blah2"
"blah2blah1"
"blahblah1"
"blahblah2"
"blahblah"
Write test cases for each of these, with your answer. Now make the tests pass. Simple!
I'm not sure there's another way but to check whether the characters are there before you compare:
String result;
if (str.indexOf('1') > -1 && str.indexOf('2') > -1 ) {
str.indexOf('2') > str.indexOf('1') ? result ="1 before 2":result="2 before 1";
}
else {
result="one of them is not there"
}
System.out.println(result);
All depends on the results you expect
String str = "blah1blah2"
int indexOf1 = str.indexOf(1);
int indexOf2 = str.indexOf(2);
if(indexOf1!=-1)
{
if(indexOf2!=-1)
{
int flag = indexOf1 - indexOf2;
if(flag<0) // 1 first
else // 2 first
}
else
{ // 1 is present, but 2 is not }
}
else
{
if(indexOf2!=-1) // 2 is present, but 1 is not
}
In Java is there a way to find out if first character of a string is a number?
One way is
string.startsWith("1")
and do the above all the way till 9, but that seems very inefficient.
Character.isDigit(string.charAt(0))
Note that this will allow any Unicode digit, not just 0-9. You might prefer:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
Or the slower regex solutions:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.
To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.
Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
IN KOTLIN :
Suppose that you have a String like this :
private val phoneNumber="9121111111"
At first you should get the first one :
val firstChar=phoneNumber.slice(0..0)
At second you can check the first char that return a Boolean :
firstChar.isInt() // or isFloat()
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
I just came across this question and thought on contributing with a solution that does not use regex.
In my case I use a helper method:
public boolean notNumber(String input){
boolean notNumber = false;
try {
// must not start with a number
#SuppressWarnings("unused")
double checker = Double.valueOf(input.substring(0,1));
}
catch (Exception e) {
notNumber = true;
}
return notNumber;
}
Probably an overkill, but I try to avoid regex whenever I can.
To verify only first letter is number or character --
For number
Character.isDigit(str.charAt(0)) --return true
For character
Character.isLetter(str.charAt(0)) --return true