Solved

trim trailing comma

Posted on 2006-11-30
24
2,010 Views
Last Modified: 2008-01-16
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?
0
Comment
Question by:domoaarongato
  • 10
  • 8
  • 3
  • +2
24 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 18043581
if (b.indexOf(',') >= 0) {
    b =a.trim()...............................
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18043589
...although the check in the code you posted should be more like

if (b.length() >= 1)
0
 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 18043639
Hi domoaarongato,

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


Regards

!i!
0
 
LVL 35

Expert Comment

by:girionis
ID: 18043666
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 18043670
b = b.replaceAll("[,:;\\-\"'\\?]+$", "");

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

Author Comment

by:domoaarongato
ID: 18043673
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
 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 18044057
Hi again domoaarongato,

NullPointerException - if replacement is null

HTH

!i!
0
 

Expert Comment

by:tonyfr
ID: 18044245
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
 

Author Comment

by:domoaarongato
ID: 18045791
ivostoykov, i don't understand you last post.

what does this mean?
HTH

!i!
0
 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 18047224
Hi domoaarongato,

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

regards

I
0
 

Author Comment

by:domoaarongato
ID: 18048671
tha tis correct.  is there a way to control if it's null or not?
0
 

Expert Comment

by:tonyfr
ID: 18051894

//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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 18056013
Hi domoaarongato,

sorry for delay... try this

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

regards

I
0
 

Author Comment

by:domoaarongato
ID: 18056202
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
 

Author Comment

by:domoaarongato
ID: 18057580
hello?
0
 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 18060671
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
 

Author Comment

by:domoaarongato
ID: 18062485
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
 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 18062580
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
 

Author Comment

by:domoaarongato
ID: 18062598
I'm not sure i follow.  do you want me to post some of my SELECT Query String?

0
 
LVL 22

Expert Comment

by:Ivo Stoykov
ID: 18062663
Hi domoaarongato,

no, just a sample - something like

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


regards

I
0
 

Author Comment

by:domoaarongato
ID: 18062692
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
 

Author Comment

by:domoaarongato
ID: 18062714
I have to go now.  I hope my above post helps a bit to explain what it is im trying to do.
0
 
LVL 22

Accepted Solution

by:
Ivo Stoykov earned 500 total points
ID: 18063078
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
 

Author Comment

by:domoaarongato
ID: 18064068
works!! :)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now