I have a scenario where i have to check if message contains any regional language then the type should be "2" or if it contains English(can contains special char, digits) language then the type should be "0".
I have tried using
for (char c: messages.get(0).message().toCharArray()) {
if (Character.UnicodeBlock.of(c) ==
Character.UnicodeBlock.DEVANAGARI) {
isHindi = true;
break;
}
}
but in java it checks for each specific language.
I want to write generalise code for that.
Thanks
English is all ASCII so you can do
if (c > 127 && Character.isLetterOrDigit(c)) // non English letter or digit.
Let's convert it into a method, it serves better.
class IndianTest {
public static void main(String args[])
{
String x = "यर";
if (textContainsIndian(x)) {
System.out.println("indian");
} else if (isEnglish(x)) {
System.out.println("english");
} else
System.out.println("another language");
}
public static boolean textContainsIndian(String text) {
for (char charac : text.toCharArray()) {
if (Character.UnicodeBlock.of(charac) == Character.UnicodeBlock.DEVANAGARI) {
return true;
}
}
return false;
}
public static boolean isEnglish(String name) {
return name.matches("[a-zA-Z0-9]+");
}
}
Now, you can modify the code as your purpose.
Related
I know this question is basic but I am looking for a less-clumsy approach to the following if statement:
if ((sOne.Contains('*')) || (sOne.Contains('/')) || (sOne.Contains('-')) || (sOne.Contains('+')) || (sOne.Contains('%'))){
I should also note that sOne.Contains() refers to the following code...
public boolean Contains(char key) {
// Checks stack for key
boolean retval = arrs.contains(key);
return retval;
}
It should also be noted that those five chars will never be changed.
You could use a breaking for-each loop over a character array:
for (char c : "*/-+%".toCharArray()) {
if (sOne.Contains(c)) {
// ...
break;
}
}
If you're extremely concerned about performance you might also want to pull out the toCharArray() call and cache the result in a static final char[] constant.
You could even use this strategy to define other convenience methods on your sOne object, like ContainsAny or ContainsAll (credit to Sina Madrid for the name ContainsAny):
public boolean ContainsAny (CharSequence keys) {
for (int i = 0; i < keys.length; i++)
if (Contains(keys.charAt(i)) return true;
return false;
}
public boolean ContainsAll (CharSequence keys) {
for (int i = 0; i < keys.length; i++)
if (!Contains(keys.charAt(i)) return false;
return true;
}
Usage would look something like this:
if (sOne.ContainsAny("*/-+%")) {
// ...
}
You can try using regular expression like this
if (sOne.matches(".*[-*/+%].*")) {
// your code
}
Somewhere, you need the characters in a list:
List<Character> keys = Arrays.asList('*', '/', '-', '+', '%');
And then you can do:
if (keys.stream().anyMatch(sOne::Contains)) {
How about this method:
Items are your keys stored in an Array.
public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
return true;
}
}
return false;
}
You don't show what arr is but since it has a contains method I'm going to assume it is a collection. So if you were to put your keys into a static collection like a Set and if arr is a collection of some type as well, you could use Collections.disjoint. disjoint returns true if there is no intersection between two collections.
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class Test {
static Set<Character> keys = new HashSet<Character>(Arrays.asList('*','/','-','+','%'));
static class SOne {
Set<Character> arrs = null;
SOne(String line) {
arrs = line.chars().mapToObj(e->(char)e).collect(Collectors.toSet());
}
public boolean Contains(Set<Character> checkset) {
return !Collections.disjoint(arrs, checkset);
}
}
static public void main(String args[]) {
SOne sOne = new SOne("Does not contain");
SOne sTwo = new SOne("Does contain a + sign");
if(sOne.Contains(keys)) {
System.out.println("Fail: Contains a key");
} else {
System.out.println("Pass: Does not contain a key");
}
if(sTwo.Contains(keys)) {
System.out.println("Pass: Contains a key");
} else {
System.out.println("Fail: Does not contain a key");
}
}
}
You could write a method like this and still re-use your existing method (substitute T for type of sOne):
static <T> boolean ContainsAny(T sOne, char... keys) {
for (char key : keys) {
if (sOne.Contains(key))
return true;
}
return false;
}
You can then invoke it like so with any number of characters to evaluate:
if (ContainsAny(sOne, '%', '_', '-')) {
//code here
}
If you're using an if statement of this form in only one place, it would be fine to keep the same structure but just format it more neatly:
if (sOne.contains('+') ||
sOne.contains('-') ||
sOne.contains('*') ||
sOne.contains('/') ||
sOne.contains('%')) {
...
}
P.S. In your method it is not necessary to define a boolean variable merely to immediately return it; you can return the other method's result directly:
public boolean contains(char key) {
// Checks stack for key
return arrs.contains(key);
}
Please also note the naming conventions: method names (contains) should start with a lower-case letter.
I am trying to calculate the number of characters in a string by using recursive method. here is my code in java
public class MainClass {
public int length(String str) {
if (str == null) {
return 0;
} else {
return length(str.substring(1))+1; // in eclipse it says : at MainClass.length(MainClass.java:12)
}
}
public static void main(String args[]) {
MainClass m = new MainClass();
System.out.println(m.length("ali"));
}
}
This line does not work : return length(str.substring(1))+1;
How can I correct the code?
Thanks
You forgot the case when your String argument is an empty string, include that in your check:
if (str == null || str.length()==0) {
return 0;
} else {
[...]
Please note that the Exception that you get contains valuable information about what's going wrong, in this case it's probably a StringIndexOutOfBoundsException because you call substring(1) on an empty String object.
It should be
public int length(String str) {
if (str==null||str.isEmpty()) {
return 0;
}else {
return length(str.substring(1))+1
}
First off, I will admit that this is an assignment of mine. however, I am at my wits end. I tried need to validate that the user input a proper expression (ie: "7 + 5;") and I managed to do it with split methods but I was told that I can't do that. I'm sure there is a simple solution to the problem but I am not seeing it.
The code is rather lengthy so I won't post it but if I will if needed.
Thanks!
Edit to answer questions: I am writing in jGrasp, so they can do whatever is on the keyboard. I was told to "Find a creative way to use substrings" which I don't know what that means. The expression needs to be Number Space operand Space number semicolon
here is what I have for the validation... I am using arrays for each character in the expression
public static boolean validFormat(String expr)
{
String tokens[] = expr.substring()
if (tokens.length == 3)
{
if (tokens[0].equals(""))
{
return false;
}
if (tokens[1].equals(""))
{
return false;
}
if (tokens[2].length < 2)
{
return false;
}
else
{
if (tokens[2].endwith(";"));
{
return false;
}
else
{
return true;
}
}
}
return false;
}
I get an error with calling the substring as well as an "else without if" error
First, you should limits the input to 6 characters using an if statement. Then use the CharAt() method to return each character to check the condition.
I was told to "Find a creative way to use substrings".
As told, try using String.substring() for the same.
public class Demo {
public static void main (String[] args) {
String exp = "7 + 5;";
System.out.printf("%s\t%b%n", exp, validate(exp));
exp = "4 + d;";
System.out.printf("%s\t%b%n", exp, validate(exp));
}
public static boolean validate(String exp) {
String n1 = exp.substring(0,1);//operand
String n2 = exp.substring(4,5);//operand
String co = exp.substring(5);//semicolon
String s1 = exp.substring(1,2);//space
String s2 = exp.substring(3,4);//space
String op = exp.substring(2,3);//operator
return num(n1) && num(n2) && semi(co) && space(s1) && space(s2) && opt(op);
}
public static boolean num(String n) {
return "0123456789".contains(n);
}
public static boolean semi(String s) {
return ";".equals(s);
}
public static boolean space(String s) {
return " ".equals(s);
}
public static boolean opt(String s) {
return "-+*%/^".contains(s);
}
}
This solution uses RegExp:
public class Demo {
public static void main (String[] args) {
String exp = "7 + 5;";
System.out.printf("%s\t%b%n", exp, validate(exp));
exp = "4 + d;";
System.out.printf("%s\t%b%n", exp, validate(exp));
}
public static boolean validate(String exp) {
return exp.matches("\\d\\s(\\+|\\-|\\*|\\/|\\^|\\%)\\s\\d\\;");
}
}
http://codingbat.com/prob/p126880
Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string.
I cannot get when it is true, it always gives false.
public boolean endOther(String a, String b)
{
//variables
a.toLowerCase();
b.toLowerCase();
String f1="";
String f2="";
int d=0;
int sum=0;
//Program code;
if(a.length()-b.length()>0)
{
(f1).equals(a);
(f2).equals(b);
d=a.length();
}
else if(a.length()-b.length()<0)
{
(f1).equals(b);
(f2).equals(a); //gett**ing bigger and lower String**
d=b.length();
}
else if((a).equals(b))
sum++;
// I think problem is because it is not enter the for.
for(int i=0; i>d; i++)
{
if((f1.substring(i,i+f2.length())).equals(f2))
sum++;
}
if(sum>0)
return true;
else
return false;
}
This is a working example of what you are trying to achieve to test in your Java IDE like Netbeans or Eclipse whatever. This is really simple, the String object has an endsWith method so why try to invent something yourself.
If you have any troubles reading this code hit me up, should be quite straight forward. You will just have to convert your string to lowercase, that's for you to add.
public class StringEnds {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.printf("String a: ");
String a = scanner.next();
System.out.printf("String b: ");
String b = scanner.next();
// Compare a and b
if (endsWith(a, b)) {
System.out.printf("Succes\n");
} else {
System.out.printf("Fail\n");
}
}
public static boolean endsWith(String firstString, String secondString) {
return firstString.endsWith(secondString) || secondString.endsWith(firstString);
}
}
Here's your codebat solution (it is quite short):
public boolean endOther(String a, String b) {
return a.toLowerCase().endsWith(b.toLowerCase()) || b.toLowerCase().endsWith(a.toLowerCase());
}
This is my answer. I tried both ways, hope it helps.
public boolean endOther(String a, String b) {
int small = Math.min(a.length(), b.length());
if (a.length()==b.length() && a.equalsIgnoreCase(b)) {
return true;
}
if (small==a.length()) {
if (b.substring(b.length()-small).equalsIgnoreCase(a)) {
return true;
}
// from here is the toLowerCase() method.
a = a.toLowerCase();
b = b.toLowerCase();
} else if (small==b.length()) {
if (a.endsWith(b)) {
return true;
}
}
return false;
}
I have a string like a>5 and b<6 or c>=7 in java
When I check whether string contains > then output is true for both > and >=
How can I restrict my check only to specific character?
How can I use matches function?
Your mistake is, you think of a lexical entity, >=, as of a "character." That will bite you more than once, as there actually are two characters, > and =, and > is indeed here. So depending on what you need, the answer may be different.
Why don't you want to see >= found?
What usage of > is of interest for you? Will e.g. <tag>some text</tag> be a proper string which you'd prefer to allow?
You want to discriminate between greater than and greater than or equal to. Why not write a method that returns the operator?
enum Operator {
...
}
public Operator getOperator(String s) {
if(s.contains(">=")) {
return Operator.GREATER_THAN_OR_EQUAL_TO;
} else if (s.contains(">") {
return Operator.GREATER_THAN;
}
}
If the input can be a complex expression that contains multiple operators, instead of contains, try using indexOf(...) and look ahead one character for the '='.
I just threw this together based on the updated specifications. Basically a real simple parser rather mechanically created: (And I'm not good with naming at 7 in the morning oh well)
public class Main {
public static void main(String[] args) {
String test = "a > b >= c > x";
Main m = new Main(test);
System.out.println(m.getTokenNumber());
test = "aasdfasdf asdfdasf";
m = new Main(test);
System.out.println(m.getTokenNumber());
}
private String input;
private int pos;
public Main(String input) {
this.input = input;
pos = 0;
}
public TokenNumber getTokenNumber() {
TokenNumber tokenNumber = new TokenNumber();
Token t = nextToken();
while (t != Token.NONE) {
tokenNumber.addToken(t);
t = nextToken();
}
return tokenNumber;
}
private Token nextToken() {
while (pos < input.length() && input.charAt(pos) != '>') pos++;
if (pos == input.length()) return Token.NONE;
pos++;
if (pos == input.length() || input.charAt(pos) != '=') return Token.GREATER;
return Token.GREATER_EQUAL;
}
enum Token {
GREATER, GREATER_EQUAL, NONE;
}
static class TokenNumber {
public int greater;
public int greater_than;
public void addToken(Token t) {
if (t == Token.GREATER) greater++;
else greater_than++;
assert t != Token.NONE;
}
public String toString() {
return String.format("Greater: %d%nGreater Than: %d", greater, greater_than);
}
}
}
"your string >".contains(">");// returns true
boolean value = Pattern.compile(">").matcher("a>5").find(); // returns true