trim trailing comma

Hi all,  i have the below code that trims trailing chars off of a string.  
String a = "a,b,c,d,e,";

String b = a.trim().substring(0, a.length() - 1);  


I intended to use it to strip "," off of my strings.  the only problem is if there is no trailing comma, or no entry at all it throws a "String index out of range: -1" error.  

IS there a condition or something i can use to fix that?
domoaarongatoAsked:
Who is Participating?
 
Ivo StoykovConnect With a Mentor Commented:
Hi domoaarongato,

//String b= (String)request.getAttribute("b");
//which will (for this example) be String b = value1,value4,value6
        String a = "value2"; // this is the value gotten by getAttribute
        String b = "value1,value4,value6,"; // these are values returned by SQL
        int cntr = 0;   // this is just for the sample
//Here comes select loop
//SELECT * from faketable
//while (results.next()) {
        while(cntr < 9) {   // this is immitation of the above while loop
//x_b= result.getString("values_for_this_example");
            String x_b = "value" + (cntr++); // this is value got by result.getString("values_for_this_example");
            System.out.println("<input type=checkbox  name=frm" + cntr +" value=\"" + x_b +"\"" + (b.indexOf(x_b) > -1 ? " CHECKED " : "") + "/>" + x_b +"<br>");
        }


regards

I
0
 
CEHJCommented:
if (b.indexOf(',') >= 0) {
    b =a.trim()...............................
}
0
 
CEHJCommented:
...although the check in the code you posted should be more like

if (b.length() >= 1)
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
Ivo StoykovCommented:
Hi domoaarongato,

import java.util.regex.*;
String b = Pattern.compile(",$").matcher (a).replaceFirst ("");


Regards

!i!
0
 
girionisCommented:
I think the best thing you could do is to use a completely different method to replace all the commas

String a = "a,b,c,d,e,";
String b = a.replaceAll("\\,", "");

This will work whether there are commas in the string or not.
0
 
CEHJCommented:
b = b.replaceAll("[,:;\\-\"'\\?]+$", "");

will do most common punctuation. Get rid of all but the comma if you like
0
 
domoaarongatoAuthor Commented:
ivostoykov.

that works for my edit screen, i think.  i'm not getting an error on my "add" screen.  the add screen and the edit screen use the same componants.  Do you know why i would get a null error on ym add screen with the above code?
0
 
Ivo StoykovCommented:
Hi again domoaarongato,

NullPointerException - if replacement is null

HTH

!i!
0
 
tonyfrCommented:
Try this, it will remove only the comma at the end if it exists

int lastComma = a.lastIndexOf(",");

//if the comma is the last character in the string then remove it
if(lastComma == a.length()-1){
    a = a.substring(0, lastComma);
}

0
 
domoaarongatoAuthor Commented:
ivostoykov, i don't understand you last post.

what does this mean?
HTH

!i!
0
 
Ivo StoykovCommented:
Hi domoaarongato,

I guess there are null values coming from womewhere and cause an error

regards

I
0
 
domoaarongatoAuthor Commented:
tha tis correct.  is there a way to control if it's null or not?
0
 
tonyfrCommented:

//checks that a is not null before you use it
if(a != null){
    a = a.replaceAll("[,:;\\-\"'\\?]+$", "");
}
else{
    //do whatever you want to do when it is null e.g.
    a="";
}
0
 
Ivo StoykovCommented:
Hi domoaarongato,

sorry for delay... try this

String b = (a != null ? Pattern.compile(",$").matcher (a).replaceFirst ("") : "");

regards

I
0
 
domoaarongatoAuthor Commented:
The last post fixes the null issue.  but there is a couple of things happening that i'm not sure how to handle.

Currently the "," is not being trimmed. IF i change replaceFirst with replaceAll and ,$ with just , it works.

The goal of this page is to set the state of a checkbox to "CHECKED" if the value from the getAttribute and the DB Select match.  This works if there is only one item in the DB.  But if there is more than one item in the DB cell (deliminated by a ",") it will not check off anything.    Is there a way to split each of the values in getAttribute and have them each match the selects so i can have all needed checkboxes checked?

Below is my entire code. For this page.  I hope it helps display want i want to do.

<%!
// database parameters
Connection dbconn;
ResultSet result;


%><%
String x_ID;
String a;
int count = 0;
// String b could have values such as: value1,value2,value3  or it might just have one value.
String b = (String)request.getAttribute("b");
String c = (b != null ? Pattern.compile(",").matcher (b).replaceAll(""): "");


%>

<%
      Class.forName("org.gjt.mm.mysql.Driver");
      dbconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx?user=root&password=");
                  
      PreparedStatement sql = dbconn.prepareStatement ("SELECT * FROM form_terms");
            //sql.setString(1, "Garage");
            result = sql.executeQuery();
%>
<%
             while(result.next())
                        {
                        x_ID = result.getString("ID");
                        a = result.getString("FORM");
                                    out.print(c);//display values for beta testing
                                    if (a.equals(c)){
                                    out.print("<input type=" +"checkbox" + "  name="+"frm" + count++ +" value=" +"" + a +""+" CHECKED/>" + a +"<br>");
                                    } else {
                                    out.print("<input type=" +"checkbox" + "  name="+"frm" + count++ +" value=" +"" + a +""+"  />" + a +"<br>");
                                    }
                         }
%>


<%
result.close();
dbconn.close();
%>
0
 
domoaarongatoAuthor Commented:
hello?
0
 
Ivo StoykovCommented:
Hi domoaarongato,

sorry for delay - had some problems...

i cannot clearly understand why are you using replaceAll - it will join all values into b single string... i.e. if

   b = "value1,value2,value3,";
after replaceAll you'll have
   "value1value2value3";

> if the value from the getAttribute and the DB Select match
you could check
1. getAttribute equals to DB Select
2. getAttribute is found as a substring of DB Select
3. DB Select is found as a substring of getAttribute

for 2 and 3 you could use indexOf - i.e.

here is a small sample

        int count = 1;
        String a = "value2";
        String b = "value1,value2,value3,";
        String c = (b != null ? Pattern.compile(",").matcher (b).replaceAll(""): "");
        System.out.println("<input type=checkbox  name=frm" + (count++) +" value=\"" + a +"\"" + (a.equals(c) ? "CHECKED" : "") + " />" + a +"<br>");
        System.err.println(a.indexOf(b));
        System.err.println(b.indexOf(a));

the output will be

<input type=checkbox  name=frm1 value="value2" />value2<br>
-1 (not match)
7(match)

I see you checked the box if a equals to c, instead you coud check it like this...

out.print("<input type=checkbox  name=frm" + (count++) +" value=\"" + a +"\" + (a.equals(c) ? "CHECKED" : "") + " />" + a +"<br>");
and where clause will becaume

           while(result.next())
           {
              x_ID = result.getString("ID");
              a = result.getString("FORM");
              out.print(c);//display values for beta testing
              out.println("<input type=checkbox  name=frm" + (count++) +" value=\"" + a +"\"" + (a.equals(c) ? "CHECKED" : "") + " />" + a +"<br>");
            }

regards

I
0
 
domoaarongatoAuthor Commented:
Hi ivostoykov,

I've implimented all of the changes above.  the "," has now been replaced with a " " and WHiLE has been modified.

The code is much cleaner now, thanks- but it still will not add CHECKED to all boxes that equal whats stored in the DB>

any ideas?
0
 
Ivo StoykovCommented:
Hi domoaarongato,

please quote few samples from DB Select and getAttribute especially those not triggering checked
without data is hard to guess...

regards

I
0
 
domoaarongatoAuthor Commented:
I'm not sure i follow.  do you want me to post some of my SELECT Query String?

0
 
Ivo StoykovCommented:
Hi domoaarongato,

no, just a sample - something like

        String a = "value2"; // getAttribute
        String b = "value1,value2,value3,"; // select


regards

I
0
 
domoaarongatoAuthor Commented:
I'll explain it as best i can.

The getAttributes are dynamially pulled from the servlet and those attributes will always equal none or more of the the values pulled from the database SELECT (posted above).

so lets pretend that the getAttrubute is:

String b= (String)request.getAttribute("b");
which will (for this example) be String b = value1,value4,value6

the DB select would look like (for this example)

SELECT * from faketable
while (results.next()) {
x_b= result.getString("values_for_this_example");
}

the end result should be

<input type ="checkbox" name="val1" value="value1"/>
<input type ="checkbox" name="val2" value="value2" CHECKED/>
<input type ="checkbox" name="val3" value="value3"/>
<input type ="checkbox" name="val4" value="value4" CHECKED/>
<input type ="checkbox" name="val5" value="value5"/>
<input type ="checkbox" name="val6" value="value6" CHECKED/>

0
 
domoaarongatoAuthor Commented:
I have to go now.  I hope my above post helps a bit to explain what it is im trying to do.
0
 
domoaarongatoAuthor Commented:
works!! :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.