(JAVA) If replacing previous if statement - java

Quick question. I have the following code:
//Cookie
if (mType.getText().toString().toLowerCase().contains("Cookie")) {
mResults.setText(mType.getText().toString().replaceAll("(?i)\\bCookie\\b", "Dough"));
}
//Cola
if (mType.getText().toString().toLowerCase().contains("Cola")) {
mResults.setText(mType.getText().toString().replaceAll("(?i)\\bCola\\b", "Sprite"));
}
I have a script which allows me to replace certain words from user input. When a user inputs the word "Cookie", the script replaces the word with "Dough". If, however, the user types in "Cookie Cola", the script only replaces the word "Cola" with "Sprite" and discards the previous if statement which replaces the word "Cookie".
So, how can I create a script which allows me to replace multiple words from input without discarding previous if statements?

You can just store it into a variable.
like:
String value = (mType.getText().toString().toLowerCase();
if(value.contains("soda")) { value = value.replaceAll("soda","cola"); }
if(...) {...}
But. Technically you are doing more work than necessary. You can chain your replacements.
String value = (mType.getText().toString().toLowerCase();
value = value.replaceAll("soda","cola").replaceAll("...","...")... //Etc.

To answer your question- in both ifs, you're calling replace on mType.getText(). But you aren't changing that value. So you're doing the second replace on the original string. Here's how the code should look like:
String text = mType.getText().toString();
text = text.replaceAll("(?i)\\bCookie\\b", "Dough");
text = text.replaceAll("(?i)\\bCola\\b", "Sprite"));
mResults.setText(text);

Chaining together multiple String.replaceAll() statements can achieve the same result without the need for if statements. For example
String result = mType.getText.toString().toLowerCase();
result = result.replaceAll("cola", "sprite")
.replaceAll("cookie", "dough"); // And so on...
mResults.setText(result);

Related

Java simplyfying a function

I have written a function that checks if a string contains certain words but am not happy with the way the code looks
SO currently i have
private String url = "validator=http://url.com;useraccount=sf4cdamloci;licence=39I8934U401;addedon=343443334;serial=7QW0-5TU8-YN9P-G4FZ;limit=123;days=10"
private String musthave ="validator,useraccount,licence,addedon,serial,limit,days"
So i wanted to check that the url contains the must have words in the string. That eg url must have validator, useraccount, licence.....
SO i have tried the following
Boolean has_validator = false;
Boolean has_licence = false;
.....//others with has_ prefix
String[] split_url = url.split(";")
for(String key_item : split_url){
String[] splitteditem = key_item.split("=");
if (splitteditem[0].equalsIgnoreCase("validator")){
has_validator = true;
}
if (splitteditem[0].equalsIgnoreCase("useraccount")){
has_useraccount = true;
}
....others as well
}
Then later i can easily check
if(has_useraccount && has_...)
The above solution works buts its not scalable as whenever i include a new must have ill have to edit my function.
Is there a better way to achieve this. Am still new to java. I have checked on regex but still i can figure our on how to achieve this.
How do i proceed
Don't use a String to represent a set of Strings. Use... a Set of String: Set<String>. Or at least an array of strings.
Then just use a loop. If any of the word in the set isn't contain in the text, you can immediately return false. If you have never returned false in the loop, then all the words are contained in the text, and you can return true.
Pseudo code:
for each word in the set
if the word is not in the text, return false
end for
return true
If you have a Collection of must-have strings, then you can do something simple like:
mustHave.stream().allMatch(url::contains)
My example isn't doing a case-insensitive check, but you get the idea.

Extract Strings between parenthese from String

I am working on my own little Script Language. Now I am stucking at the Script Reader which reads the file and converts it into the Script Parts (variables, functions, if clauses etc). I hava String which saves the Script File content in one line like so:
mega = "";test(){hallo();test = "";if(){p2 = -1;}else{p1 = "";}hi = 0;}
Now my Problem. I want to get the strings between the parentheses for if clauses and the function (which is around the if clause). I tried it with regex:
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(example);
while(m.find()) {
System.out.println(m.group(1));
}
But then I get the content between the first parenthese of the function test(){ and the first parenthese that clauses the if clause. How can I extract the Strings between the if clause, else clause and the function?
EDIT:
This is want I want to get out after the extraction:
For the If: p2 = -1;
For the Else: p1 = "";
And for the Function arround:
hallo();test = "";if(){p2 = -1;}else{p1 = "";}hi = 0;
EDIT 2:
I would like to have it recursive to its endless (when in the if clause is another etc.)
I think that regular expressions will not do that. You are looking after correspondent pairs of curly brackets.
Reminds me of RegEx match open tags except XHTML self-contained tags.

Java - Changing multiple words in a string at once?

I'm trying to create a program that can abbreviate certain words in a string given by the user.
This is how I've laid it out so far:
Create a hashmap from a .txt file such as the following:
thanks,thx
your,yr
probably,prob
people,ppl
Take a string from the user
Split the string into words
Check the hashmap to see if that word exists as a key
Use hashmap.get() to return the key value
Replace the word with the key value returned
Return an updated string
It all works perfectly fine until I try to update the string:
public String shortenMessage( String inMessage ) {
String updatedstring = "";
String rawstring = inMessage;
String[] words = rawstring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
for (String word : words) {
System.out.println(word);
if (map.containsKey(word) == true) {
String x = map.get(word);
updatedstring = rawstring.replace(word, x);
}
}
System.out.println(updatedstring);
return updatedstring;
}
Input:
thanks, your, probably, people
Output:
thanks, your, probably, ppl
Does anyone know how I can update all the words in the string?
Thanks in advance
updatedstring = rawstring.replace(word, x);
This keeps replacing your updatedstring with the rawstring with a the single replacement.
You need to do something like
updatedstring = rawstring;
...
updatedString = updatedString.replace(word, x);
Edit:
That is the solution to the problem you are seeing but there are a few other problems with your code:
Your replacement won't work for things that you needed to lowercased or remove characters from. You create the words array that you iterate from altered version of your rawstring. Then you go back and try to replace the altered versions from your original rawstring where they don't exist. This will not find the words you think you are replacing.
If you are doing global replacements, you could just create a set of words instead of an array since once the word is replaced, it shouldn't come up again.
You might want to be replacing the words one at a time, because your global replacement could cause weird bugs where a word in the replacement map is a sub word of another replacement word. Instead of using String.replace, make an array/list of words, iterate the words and replace the element in the list if needed and join them. In java 8:
String.join(" ", elements);

Give comma separated strings as input to sql "IN" clause [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
creating comma seperated string to be given as input to sql “IN” clause
HI,
i have to implement multiple select dropdown,and the selected values shud be formatted to be input to "IN" clause of sql.
Am storing the selected values in a string.But there is no delimiter between values ,so i cannot split the string.Are there any other methods for the string formatting.
Fun solution: Add the values to ArrayList or LinkedList, the call toString(). And replace '['->'(', replace ']'->')'.
If you had a collection of strings and then copied them to 1 string without delimiters you cannot separate them again. Just do not do this. If you still have problems please send more details about your task.
If you know the values of the dropdown and all values are unique and not subsets of each other, then you can use String#contains() or regular expressions to test, which values have been selected.
But it's by far easier to simply add some trivial delimiter (like the common ";") while concatenating the String that holds the selection.
Example for the contains approach
String[] legalValues = {"YES","NO","MAYBE"};
String result = getSelection(); // returns a String like "MAYBEYES"
StringBuilder inClauseBuilder = new StringBuilder();
boolean isFirst = true;
for (String legalValue:legalValues) {
if (!result.contains(legalValue)
continue;
if (isFirst) {
isFirst = false;
} else {
inClauseBuilder.append(",");
}
inClauseBuilder.append("\"").append(legalValue).append("\"");
}
String inClause = inClauseBuilder.toString();
Note - this approach will fail as soon as you have legal values like
String[] legalValues = {"YES","NO","MAYBE-YES", "MAYBE-NO"};
^^^ ^^ ^^^ ^^

printing elements in a nice format

I have a simple, general question regarding a real small issue that bothers me:
I'm printing a list of elements on the fly, so I don't have prior knowledge about the number of printed elements. I want a simple format where the elements are separated by a comma (elem1, elem2...) or something similar. Now, if I use a simple loop like:
while(elements to check) {
if (elem should be printed) {
print elem . ","
}
}
I get a comma after the last element...
I know this sounds quite stupid, but is there a way to handle this?
Let's assume that "should be printed" means "at least one non-whitespace character. In Perl, the idiomatic way to write this would be (you'll need to adjust the grep to taste):
print join "," => grep { /\S/ } #elements;
The "grep" is like "filter" in other languages and the /S/ is a regex matching one non-whitespace character. Only elements matching the expression are returned. The "join" should be self-explanatory.
perldoc -f join
perldoc -f grep
the way of having all your data in an array and then
print join(',', #yourarray)
is a good one.
You can also, after looping for your concatenation
declare eltToPrint
while (LOOP on elt) {
eltToPrint .= elt.','
}
remove the last comma with a regex :
eltToPrint =~s/,$//;
ps : works also if you put the comma at the beginning
eltToPrint =~s/^,//;
Java does not have a build-in join, but if you don't want to reinvent the wheel, you can use Guava's Joiner. It can skipNulls, or useForNull(something).
An object which joins pieces of text (specified as an array, Iterable, varargs or even a Map) with a separator. It either appends the results to an Appendable or returns them as a String. Example:
Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Harry", null, "Ron", "Hermione");
This returns the string "Harry; Ron; Hermione". Note that all input elements are converted to strings using Object.toString() before being appended.
Why not add a comma BEFORE each element (but the first one)? Pseudo-code:
is_first = true
loop element over element_array
BEGIN LOOP
if (! is_first)
print ","
end if
print element
is_first = false
END
print NEWLINE
I guess the simplest way is to create a new array containing only the elements from the original array that you need to print (i.e. a filter operation). Then print the newly created array, preferably using your language's built-in array/vector print/join function.
(In Perl)
#orig=("a","bc","d","ef","g");
#new_list=();
for $x(#orig){
push(#new_list,$x) if (length($x)==1);
}
print join(',',#new_list)."\n";
(In Java)
List<String> orig=Arrays.asList(new String[]{"a","bc","d","ef","g"});
List<String> new_list=new ArrayList<String>();
for(String x: orig){
if (x.length()==1)
new_list.add(x);
}
System.out.println(new_list);
You have several options depending on language.
e.g. in JavaScript just do:
var prettyString = someArray.join(', ');
in PHP you can implode()
$someArray = array('apple', 'orange', 'pear');
$prettyString = implode(",", $someArray);
if all else fails, you can either add the comma after every entry and trim the last one when done, or check in you while/foreach loop (bad for perf) if this is not the last item (if so, add a comma)
update: since you noted Java... you could create a method like this:
public static String join(String[] strings, String separator) {
StringBuffer sb = new StringBuffer();
for (int i=0; i < strings.length; i++) {
if (i != 0) sb.append(separator);
sb.append(strings[i]);
}
return sb.toString();
}
update 2: sounds like you really want this then if you are not outputting every element (pseudo-code):
first = true;
for(item in list){
if(item meets condition){
if(!first){
print ", ";
} else {
first = false;
}
print item;
}
}

Categories

Resources