I need to compare two strings.
The input value is like
SELECT * FROM ds WHERE ds.age='24';
The text against which it needs to be compared being
SELECT * FROM ds WHERE ds.status='VALID' AND ds.age='24';
Since "ds.status='VALID' AND" is a static string, I thought of inserting it into the input and then compare it with the original string.
So I created a StringBuilder object and
query.insert(query.indexOf("WHERE"), "ds.status='VALID' AND");
but the output was
SELECT * FROM ds ds.status='VALID' AND WHERE ds.age='24';
Also, indexOf() cannot be inputted with a static position since it can vary with the input.
Is there any way to find the index of the last letter of the word "WHERE"?
The work-around I found is
String query = query.replace("WHERE", "WHERE ds.status='VALID' AND");
Is this the best possible method?
query.insert(query.indexOf("WHERE") + "WHERE".length(), " ds.status='VALID' AND");
I think the replace is a lot cleaner and easier to read - like Peter Lawrey's comment:
query.replace(" WHERE ", " WHERE ds.status='VALID' AND ");
No having to worry about fencepost errors or magic numbers and so much clearer in intent!
EDIT
That would be:
query.toString().replace(" WHERE ", " WHERE ds.status='VALID' AND ");
(Replace on StringBuilder takes indexes)
You can do something like this -
StringBuffer str = new StringBuffer("SELECT * FROM ds WHERE ds.age='24'");
str.insert(str.lastIndexOf("WHERE") + 6, "ds.status='VALID' AND ");
Related
I want to know why we concatenate a dummy string with a variable while printing its value.
Eg.
system.out.print(var + " ");
Concatenation with an empty string is a technique some developers use to convert any value to a string. It's unnecessary with System.out.print as that accepts any value anyway. I prefer using String.valueOf anyway:
String text = String.valueOf(variable);
This is clearer in terms of the purpose being converting a value to a string, rather than concatenation.
However, in the case you've given, it's possible that the developer wasn't just using concatenation for that purpose - but actually to get the extra space. For example:
int var1 = 1, var2 = 2, var3 = 3;
System.out.print(var1 + " ");
System.out.print(var2 + " ");
System.out.print(var3 + " ");
Those will all print on the same line:
1 2 3
Other options include:
Using a StringBuilder to build up the string before printing it
Putting it all into a single System.out.print call: System.out.print(var1 + " " + var2 + " " + var3);
Using printf instead: System.out.printf("%d %d %d", var1, var2, var3);
Extremely sorry. The question was l1.setText(var+" "); and it is done because a text field cannot take an integer value, so we concatenate a dummy string at the end of it, so the integer value in var can be printed.
Thank you all for helping me out!
I am trying to implement a functionality in android app where as user keys in the numbers, I want to incrementally search those numbers in Phone book (the generic phone book search) and display result.
For this, I am using
Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(aNumber));
This seems to work for most of the cases and is handling search for ' ' etc.
There are 2 issues that I am not able to resolve :
It does not ignore the country code.
So as an e.g. if I have a number : +9199776xx123
When my search string is +9199, the result comes up. While if my search string is 9977, it does not come up.
It does not search from between.
When my search string is 776, then also result does not come up.
So the behavior of CONTENT_FILTER_URI of Phone is not exactly clear to me.
P.S. : I have tried PhoneLookup but for some reason, it does not throw any result. My belief is that it might not be capable to searching partial numbers.
After quite a lot or research, I was able to find the answer. Now, I search on both the columns, Number and normalized number. This takes care of both the cases since normalized number contains country code in the number.
My selection string looks like :
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE ? OR "
+ ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER + " LIKE ?";
Phone.CONTENT_FILTER_URI is built for speed, but it's not perfect, as you've noticed.
You can use the plain Phone.CONTENT_URI to process any kind of request you want.
e.g.:
String partialPhone = "9977";
String[] projection = new String[] {Phone.DISPLAY_NAME, Phone.NUMBER, Phone. NORMALIZED_NUMBER};
String selection = "(" + Phone.NUMBER + " LIKE %" + partialPhone + "%) OR (" + Phone.NORMALIZED_NUMBER + " LIKE %" + partialPhone + "%)";
Cursor c = cr.query(Data.CONTENT_URI, projection, selection, null, null);
I created this Java method:
public String isInTheList(List<String> listOfStrings)
{
/*
* Iterates through the list, and if the list contains the input of the user,
* it will be returned.
*/
for(String string : listOfStrings)
{
if(this.answer.matches("(?i).*" + string + ".*"))
{
return string;
}
}
return null;
}
I use this method in a while block in order to validate user input. I want to check if that input matches the concatenation of two different predefined ArrayLists of Strings.
The format of the input must be like this:
(elementOfThefirstList + " " + elementOfTheSecondList)
where the Strings elementOfThefirstList and elementOfTheSecondList are both elements from their respective list.
for(int i = 0; i < firstListOfString.size(); i++)
{
if(userInput.contains(firstListOfString.get(i) + " " + userInput.isInTheList(secondListOfString)))
{
isValid = true;//condition for exit from the while block
}
}
It work if the user input is like this:
elementOfThefirstList + " " + elementOfTheSecondList
However, it will also work if the user input is like this:
elementOfThefirstList + " " + elementOfTheSecondList + " " + anotherElementOfTheFirstList
How can I modify my regular expression, as well as my method, in order to have exactly one repetition of elements in both lists concatenated with a space between them?
I tried with another regular expression and I think that I will use this: "{1}". However, I am not able to do that with a variable.
With the information you provide as to how you are getting this issue, there is little that can be said about how to fix it. I strongly encourage you to look at this quantifiers tutorial before moving forward.
Let's look at some solutions.
For example, lets look at the line:if(this.answer.matches("(?i).*" + string + ".*"))What you are trying to do is to see if this.answer contains string, ignoring case (I doubt you need the last .*). But you are using a Greedy Quantifier to compare them. If the issue is arising due to an input error in this comparison, I would consider looking at the linked tutorial for Reluctant Quantifiers.
Okay, so it wasn't a quantifier issue. The other possible fix may be this block of code:
for(int i = 0; i < firstListOfString.size(); i++)
{
if(userInput.contains(firstListOfString.get(i) + " " + userInput.isInTheList(secondListOfString)))
{
isValid = true;//condition for exit from the while block
}
}
I don't know you you got userInput to have the containsmethod, but I assume that you used containment to call the String method. If this is the case, there could be a solution to the issue. You would only have to state that it is valid if and only if it is equal to an element from the first list and a matching element from the second string.
The final solution I have for you is simple. If there are no other spaces present within the list elements, you could split the concatenated String on a space and check how many elements the resulting array contains. If it is greater than two, then you have an invalid concatenation.
Hopefully this helps!
I have got a String which reads "You cannot sit on that " + entity.getEntityType().toLowerCase() + "!";. Which returns an upper case, which is why I convert it to lower case.
However, how can I get the first letter ONLY, and turn it into an upper case?
A one-liner solution would be preferred, however beggars cant be choosers.
In java, if you do any manipulation to String, it will create a new string in the memory.
Here's, how to do it:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
It's more efficient to treat the first character what it is - a character and not a String:
String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);
The first thing it came to my mind was this
int x = a.codePointAt(0)-32;
a=a.replace(a.charAt(0), (char) x);
You can just use something like this:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
On the other hand is isn't bad to take a look at the guava libraries.
String output = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, entity.getEntityType()));
For this case only it will be overkill but it has a lot of other usefull utilities (Not only for String manipulation)
I am trying to get two string firstName and lastName which is fully in uppercase and tring to convert all the characters except the first one in lowercase and concatenate the resultant strings.
firstname="TOM";
lastName="HARRIS";
Output is : Tom Harris
I achieved it by doing:
String name =
firstName.substring(0,1).toUpperCase()
+ firstName.substring(1).toLowerCase()
+ " "
+ lastName.substring(0,1).toUpperCase()
+ lastName.substring(1).toLowerCase();
but is there any other way of doing ? a more efficient way ?
Yes, you can use the method WordUtils.capitalizeFully() from Apache Commons Lang:
String name = WordUtils.capitalizeFully(firstName + " " + lastName);
As Strings are immutable in Java, when doing that many concatenations it's more efficient to use a StringBuilder, like so:
StringBuilder s = new StringBuilder();
String name = s.append(firstName.substring(0,1).toUpperCase())
.append(firstName.substring(1).toLowerCase())
.append(" ")
.append(lastName.substring(0,1).toUpperCase())
.append(lastName.substring(1).toLowerCase()).toString();
As this only creates 2 objects: the String and the StringBuilder, rather than 4* as before.
*Concatenating a String literal is done at compile time, so adding the " " does not create a new object.
If you need a little more control in building up Strings Snippetory may help
Syntaxes.XML_ALIKE.parse("{v:x case='camelizeUpper' delimiter=' '}").append("x", firstName).append("x", lastName).toString();