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 ?
Related
My teacher asked us to design a program that receives a string value and then converts all numeric characters to *.
I tried the replaces method but it did not work.
You have to use regular expressions. In addition to that, since you want to replace all numbers, you should use replaceAll instead of replace. This should do the job:
s.replaceAll("[0-9]", "*")
Use it to instead of
s.replaces(...)
I am using Pattern.compile() to find if a text string contains two other strings. But it needs to be in one regex pattern.
For example the string must have "StringOne" and "StringTwo" in it.
I could do Pattern.compile("(StringOne StringTwo|StrinTwo StringOne"), but both strings are quite long and I want to see if I can compress it.
If I do "(StringOne )?StringTwo( StringOne)?" it would match "StringTwo" and "StringOne StringTwo StringOne".
Use this regex:
^(?=.*\\bStringOne\\b)(?=.*\\bStringTwo\\b)
This uses two look-aheads anchored to start of input to assert that both strings appear somewhere
Edit:
Added word boundaries \b to ends of strings to prevent matches of one string within another, although this was not a stated requirement of the question.
There is question of speed.
You could probably use lookaheads to accomplish this, but it's costly speed-wise. lookaheads are really expansive on long strings.
If the strings are long, the faster approach would be to do two separate matches.
If you really need to do one, use your original way string A string B|String B String A
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.
i need to search in the thousands strings of a array for the character '. If i find the character ', then, i must put another character ' before it. Like this: ''
For example, imagine that i have a 1000 strings on this array: List <String> strings. For example, this is one of my strings:
"I have some Levi's shoes."
The algorithm must transform the string into: "I have some Levi''s shoes."
I must check all the thousands of strings of my array strings
Wich is the best efficient way to achieve this?
Thanks
The simplest way is to iterate over the string in your array, and use replace(CharSequence, CharSequence) on each, assigning the results back into the array.
For a single string:
myString = myString.replace("'", "''");
For a List of strings:
for(int i=0;i<myList.size();i++){
myList.put(i, myList.get(i).replace("'", "''"));
}
As Jon Skeet pointed out, replace is better than replaceAll because you don't have to compile and run a regex for a simple character sequence.
You can use replaceAll method or replace. It simply iterate over String and replace characters.Both of this method compile regex and use StringBuffer. You don't need regex in you case. Probably you can slightly boost it with your implementation, you don't need regex, you can try StringBuilder instead, it's not synchronized.
You are essentially doing a worst case text search -- that being a single character. I think the only way to get a real speedup is to divide the work and use more threads to do it faster. Multi-core CPU or GPU can really speed up your search, and I know there are Java bindings / libraries for both.
try StringUtils.replace(String str, String searchChars, String replaceChars) (apache commons)
Given a string
7 + 45 * 65
How to check whether a given character of this string is an integer and then store the whole integer value in an integer variable?
E.g. for 65, check if 6 is an integer, if yes, then store 65 in another integer variable. You can assume that the string can be converted into a character array.
Given that this looks like homework below are some tips for a simple way to parse and store each integer value.
Check out the API documentation for the Character class. This will contain methods for determining whether a character is a digit.
Consider using a StringBuilder to store the intermediate numerical result as you read in each digit of the number.
Check the Integer class API for methods to help with parsing the String value (stored within your StringBuilder) and turning it into an int.
Finally, consider using a List (e.g. LinkedList) to store the int value.
For a quick and dirty soluiton I would use StringTokenizer and try { Integer.parseInt() } catch (NumberFormatException){}
Check out this post on exactly the same topic:
Java Programming - Evaluate String math expression
It looks like BeanShell has the cleanest method to do what you need. You could also try the JavaScript Engine method (although BeanShell looks much cleaner to me).
Easiest solution would be to use java.util.Scanner. You can set Scanner.useDelimeter("\\D+") which will mean skip any non-digit characters, and then call Scanner.nextInt() to get next Integer from the String.
If you want to work with characters, then use Character.isDigit(char c).