How to test data within a string without using another string - java

Is it possible to test the data within a string without using another string? For example, if I wanted to test whether String size=("large") is it possible without having to create a second string with the value as large and comparing it using .equals? Is it possible to test case as well (i.e. not using .equalsignorecase)?

In a conditional statement you need to compare using the .equals(....) method or .equalsIgnoreCase(...). As far as testing for upper and lower case of characters, take a look at the Character class in the javadocs. I believe you'll find methods like: isLetter() and isUpperCase() and isLowerCase(). Just use a loop to iterate over the string and evaluate over every character.

Related

How to split string if splitting character is dynamic or unknown?

I want to make a Java program in which I want to take a String as a input. The string will have two integer numbers and operation to be performed.
eg. 25+85
or 15*78
The output will the solution of the string.
But I don't know how to split the string because operator sign is not known before execution.
You would want to check what operation it is using by using String.contains("+"); and checking all the other operators you want to support. Then split wherever that operator is, String.split("+"). From there parse the output of String.split("+") by using Integer.parseInt(String s) and then return the sum. Pretty simple, good luck.
You can use the split() method of the String class to split the input at non-digit characters:
input.split("\\D");
This will give you an array containing only the numbers.
I guess you also want to get the operator somehow? Although it's not the most elegant way, you might want to start with input.replaceAll("[^\\*\\+\\-\\/]", "") to remove everything that's not an operator, but you will still have to do some careful input filtering. What if i type 5+4*6 oder 2+hello ?

Split result not usable on android

I have a string that I split, it works perfectly until i want to use it : when I use a 'for' to read what a have in my String table I shows exactly what I want, but when I use if(MyStringTable[1] == "a") it isn't true, even though I just saw that MyStringTable[1] was equal to "a".
My string table is "static" declared.
I'm wondering if there is an invisible character or something that has been created with the split.
In terms of Strings, use .equals() in order to check if a String is equal to another. If one of them is a character, cast it previously to a String using .toString() to make it match this approach.

Elegant way to do variable substitution in a java string

Pretty simple question and my brain is frozen today so I can't think of an elegant solution where I know one exists.
I have a formula which is passed to me in the form "A+B"
I also have a mapping of the formula variables to their "readable names".
Finally, I have a formula parser which will calculate the value of the formula, but only if its passed with the readable names for the variables.
For example, as an input I get
String formula = "A+B"
String readableA = "foovar1"
String readableB = "foovar2"
and I want my output to be "foovar1+foovar2"
The problem with a simple find and replace is that it can be easily be broken because we have no guarantees on what the 'readable' names are. Lets say I take my example again with different parameters
String formula = "A+B"
String readableA = "foovarBad1"
String readableB = "foovarAngry2"
If I do a simple find and replace in a loop, I'll end up replacing the capital A's and B's in the readable names I have already replaced.
This looks like an approximate solution but I don't have brackets around my variables
How to replace a set of tokens in a Java String?
That link you provided is an excellent source since matching using patterns is the way to go. The basic idea here is first get the tokens using a matcher. After this you will have Operators and Operands
Then, do the replacement individually on each Operand.
Finally, put them back together using the Operators.
A somewhat tedious solution would be to scan for all occurences of A and B and note their indexes in the string, and then use StringBuilder.replace(int start, int end, String str) method. (in naive form this would not be very efficient though, approaching smth like square complexity, or more precisely "number of variables" * "number of possible replacements")
If you know all of your operators, you could do split on them (like on "+") and then replace individual "A" and "B" (you'd have to do trimming whitespace chars first of course) in an array or ArrayList.
A simple way to do it is
String foumula = "A+B".replaceAll("\\bA\\b", readableA)
.replaceAll("\\bB\\b", readableB);
Your approach does not work fine that way
Formulas (mathematic Expressions) should be parsed into an expression structure (eg. expression tree).
Such that you have later Operand Nodes and Operator nodes.
Later this expression will be evaluated traversing the tree and considering the mathematical priority rules.
I recommend reading more on Expression parsing.
Matching Only
If you don't have to evaluate the expression after doing the substitution, you might be able to use a regex. Something like (\b\p{Alpha}\p{Alnum}*\b)
or the java string "(\\b\\p{Alpha}\\p{Alnum}*\\b)"
Then use find() over and over to find all the variables and store their locations.
Finally, go through the locations and build up a new string from the old one with the variable bits replaced.
Not that It will not do much checking that the supplied expression is reasonable. For example, it wouldn't mind at all if you gave it )A 2 B( and would just replace the A and B (like )XXX 2 XXX(). I don't know if that matters.
This is similar to the link you supplied in your question except you need a different regular expression than they used. You can go to http://www.regexplanet.com/advanced/java/index.html to play with regular expressions and figure out one that will work. I used it with the one I suggested and it finds what it needs in A+B and A + (C* D ) just fine.
Parsing
You parse the expression using one of the available parser generators (Antlr or Sable or ...) or find an algebraic expression parser available as open source and use it. (You would have to search the web to find those, I haven't used one but suspect they exist.)
Then you use the parser to generate a parsed form of the expression, replace the variables and reconstitute the string form with the new variables.
This one might work better but the amount of effort depends on whether you can find existing code to use.
It also depends on whether you need to validate the expression is valid according to the normal rules. This method will not accept invalid expressions, most likely.

Java Regex - Trying to use regex to get an array of "function" arguments

I have a bunch of strings representing mathematical functions (which could be nested and have any number of arguments), and I want to be able to use regex to return an array of strings, each string being an argument of the outer-most function. Here's an example:
"f1(f2(x),f3(f4(f5(x,y,z))),f(f(1)))"
I would want a regex pattern that I could use to somehow get an array of all the arguments of f1, which in this case are the strings "f2(x)", "f3(f4(f5(x,y,z)))", and "f(f(1))". There will be no spaces in the input string.
Thank you very much to anyone who can help.
I don't think this can be done with regexes alone.
This would probably require being able to identify balanced parentheses -- for example, once we've parsed f1(f2(x), the next character could either be a ) or a , -- and that's a canonical example of something that can't be done with regexes, but requires a more sophisticated parser.

search string inside a word in java

I want to search a word inside a string :
For example let the String be "ThisIsFile.java"
and let i want to search "File.java" or "IsFile"
This is something like sql 'like' query but unfortunately i am not
getting that string from database.
Please suggest me any good solution for this.
Thanks
There's a variety of ways of achieving this and the method you choose will depend on the complexity of your queries. For a simple plain symbol/word match the String class provides a contains method that takes a single parameter, the String to search for - and returns true if it occurs within the search String.
bool containsFile = myString.contains("file");
Do you mean:
if (haystack.contains(needle))
? Note that this won't respect word boundaries or anything like that - it just finds if one string (needle) is a substring in another (haystack).
Try using String.contains(). Also, check out the documentation for more information about the method
You should be able to use
String.contains("some string");

Categories