I am having string like as follow
String first = "UPPER(substr(con.table_name,1,4)) <> 'BIN$' order by name"
String second = "and constraint_type = 'C' "
I have to insert the second string after first string of UPPER(substr(con.table_name,1,4)) <> 'BIN$'
My result
String c = "UPPER(substr(con.table_name,1,4)) <> 'BIN$' and constraint_type = 'C' order by name"
Strings are immutable so first of all you can't change the string referred to by a. You need to create a new string and reassign a to refer to the new string:
To insert the b string before the order by part in the a string, you could do
int i = a.indexOf("order by");
String newString = a.substring(0, i) + b + a.substring(i);
The result is
UPPER(substr(con.table_name,1,4)) <> 'BIN$' and constraint_type = 'C' order by name
Have a look at java.text.MessageFormat.
That allows to have a format string (like UPPER(substr(con.table_name,1,4)) <> 'BIN$' {0} order by name) formatted with parameters (your param would be and constraint_type = 'C').
If you do have control over a, one of the other answers is probably the best way to go around this.
Assuming you have no control on the contents of string a, you could call a.split("order by"), save the two resulting pieces into two variables a1 and a2 and creating a new string with b between a1 and a2. Something like this (untested):
String[] temp = a.split("order by");
String result = temp[0] + " " + b + " order by " + temp[1];
Again, I haven't really tested this, but you get the idea.
On another note, it looks like you're doing some bare sql manipulation there. Don't do this, my friend. Your code will be pretty vulnerable to sql injection. Use prepared statements instead.
Related
This is a dumb question, but how can I delete a trailing AND in a sql statement in Java?
I'm dynamically generating the statement based on the Profile object I give it. So, if the object has "name = person1" and "address = example road", the statement should be:
select * from Profile where name = 'person1' and address = 'example road'
The issue is that I'm using a for loop to iterate through the declared fields of the object, and so it adds an extra AND to the end:
select * from Profile where name = 'person1' and address = 'example road' and
What would be the best way to get rid of a trailing AND?
You should be using a prepared statement. Building a query like this leaves you open to SQL injection and other attacks.
If you must continue with your current approach, then a quick fix would be to strip off the final AND via regex:
String sql = "select * from Profile where name = 'person1' and address = 'example road' and";
sql = sql.replaceAll("(?i)\\s+and$", "");
Demo
Some would simply trim the final "and" from the end of the resulting string, but it's usually better to avoid writing the final and in the first place.
If your loop looks something like this:
for (String sqlCondition : sqlConditionsList) {
sqlStatement.append(sqlCondition).append(" and ");
}
Then I'd recommend changing it to something like this:
boolean separatorNeeded = false;
for (String sqlCondition : sqlConditionsList) {
if (separatorNeede) {
sqlStatement.append(" and ");
}
sqlStatement.append(sqlCondition);
separatorNeeded = true;
}
This will only add the "and" separator when it's actually needed, between consecutive items from the list you are iterating.
You should use prepared statements or ORM. But if you still want to do that in this error-prone way, you can do it like this:
public static void main(String args[]) {
String[] params = new String[3];
params[0] = "x = y";
params[1] = "z = a";
params[2] = "b = d";
String result = String.join(" and ", params);
System.out.println(result);
}
Using join method is imho better solution than messing with trailing and.
I'm a student that is learning Java, and I have this code:
lletres = lletres.replace(lletres.charAt(2), codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres is a string, and it's like this
lletres = "BBB"
The result is "CCC" and I only want to change the last B, so the result can be like this: "BBC".
Reading the documentation for String.replace should explain what happened here (I marked the relevant part in bold):
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
One way to solve it is to break the string up to the parts you want and then put it back together again. E.g.:
lletres = lletres.substring(0, 2) + (char)(lletres.charAt(2) + 1);
As others pointed replace() will replace all the occurrences which matched.
So, instead you can make use of replaceFirst() which will accept the regx
lletres = lletres.replaceFirst( lletres.charAt( 2 ) + "$", (char) ( lletres.charAt( 2 ) + 1 ) + "" )
You could use StringBuilder for your purpose:
String lletres = "BBB";
String codi = "CCC";
StringBuilder sb = new StringBuilder(lletres);
sb.setCharAt(2, codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres = sb.toString();
If you need to change only the last occurrence in the string, you need to split the string into parts first. I hope following snippet will be helpful to you.
String lletres = "BBB";
int lastIndex = lletres.lastIndexOf('B');
lletres = lletres.substring(0, lastIndex) + 'C' + lletres.substring(lastIndex+1);
This code will find index of last letter B and stores it in lastIndex. Then it splits the string and replaces that B letter with C letter.
Please keep in mind that this snippet doesn't check whether or not the letter B is present in the string.
With slight modification you can get it to replace whole parts of the string, not only letters. :)
Try this one.
class Rplce
{
public static void main(String[] args)
{
String codi = "CCC";
String lletres = "BBB";
int char_no_to_be_replaced = 2;
lletres = lletres.substring(0,char_no_to_be_replaced ) + codi.charAt(codi.indexOf(lletres.charAt(char_no_to_be_replaced )) + 1) + lletres.substring(char_no_to_be_replaced + 1);
System.out.println(lletres);
}
}
use this to replace the last character
lletres = lletres.replaceAll(".{1}$", String.valueOf((char) (lletres.charAt(2) + 1)));
suppose you have dynamic value at last index and you want to replace that value will increasing one then use this code
String lletres = "BBB";
int atIndex = lletres.lastIndexOf('B');
char ReplacementChar = (char)(lletres.charAt(lletres.lastIndexOf('B'))+1);
lletres= lletres.substring(0, atIndex)+ReplacementChar;
System.out.println(lletres);
output
BBC
I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in Chicago,IL, everything works, but if they type in Chicago, IL, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
I have also tried this:
String state = location.substring(location.indexOf(",".trim()) + 1);
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
How can I fix this, so that even if a user puts in 2 or 4 spaces after
the comma it still shows the same results as the first case?
you can use location.replaceAll(" ", "")
for extracting the location into city,state
you can use split() method as
String location[]=location.split(",");
Now
String city=location[0];
String state=location[1];
EDIT:(for Whome)
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
you were in the right direction by using trim(). However, you put it in the wrong place.
",".trim() will always yield ",". you want to trim the result of the substring operation:
String state = location.substring(location.indexOf(",") + 1).trim();
Trim the entire result. For example:
String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();
try using java.lang.String trim() function in the correct place.
trim on ",".trim() will produce ",".
Need to trim() the final result.
if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}
Use
String state = location.substring(location.indexOf(",") + 1).trim();
Instead of
String state = location.substring(location.indexOf(",".trim()) + 1);
That should work.
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();
I would like to know if when I place a sql query using java , does it retain the new lines?
for instance if i have
"IF EXISTS (SELECT * FROM mytable WHERE EMPLOYEEID='"+EMPID+"')"+
"UPDATE myTable SET ....)"
So after the "+" sign in the first line the UPDATE follows, does it maintain the new line when it is being passed to the database?
Thank you
No. For the query to work successfully you will have to add a space before UPDATE or after ).
Firstly, there is no newline in the example source code to "maintain" ...
Secondly, your problem is with Java rather than SQL. You will only get an newline into a Java String if you put it there explicitly; e.g.
// No newline in this string
String s = "a" +
"b";
// Line break in these strings
String s = "a" + "\n" + "b";
String s2 = "a\nb";
String s3 = "a" + System.getProperty("line.separator") + "b";
Finally, in your example, a space or TAB will do just as well as a line break.