-
String compare issues?
I am trying to compare two strings using the .equals() option. I am obtaining a value from a JDBC connection and trying to validate it against a user entered string, however it always fails. I have the following code -
String search = request.getParameter("usercn"); //get usercn from HTML form
while (rs.next()) {
String result = rs.getString(1); //get the current loop value
out.println("Current node:" + result + "<br>"); //print out current value
out.println("search:" + search + "<br>"); //print out user string
String r1 = new String (result);
String r2 = new String (search);
out.println("r1:" + r1 + "<br>"); // print out r1 value
out.println("r2:" + r2 + "<br>"); //print out r2 value
out.println(r1.equalsIgnoreCase(r2)); //debug - print out true/false
if (r1.equalsIgnoreCase(r2)){
String match = "true";
out.println("match" + r1);}
what I see is the following -
r1:root
r2:root
false
even though the strings appear the same, the comparison is always false.
Any thoughts??
-
Hi,
One small suggestion.u trim that string value and try like this below
r1.trim().equalsIgnoreCase(r2.trim())
-
String search ="";
if((request.getParameter("usercn") !=null) ||( request.getParameter("usercn").length() != 0) ||(request.getParameter("usercn") != ""))
{
search = request.getParameter("usercn");
}
while (rs.next()) {
//Here dont retreive via numbers.Readability sake retreive via columnName
String result = rs.getString(1); //get the current loop value
out.println("Current node:" + result + "<br>"); //print out current value
out.println("search:" + search + "<br>"); //print out user string
//The below lines are not needed.Already u are having string
//String r1 = new String (result);
//String r2 = new String (search);
out.println(result.trim().equalsIgnoreCase(search. trim())); //debug - print out true/false
if (r1.equalsIgnoreCase(r2)){
String match = "true";
out.println("match" + r1);}
-
Thanks! Trimming the string fixed the issue.