How to replace esacape(\n \t) charecters and ' charecter in java

Most of the times while dealing with the Strings in the Java many of us encountered this kind of situation ... the best solution I follow for this is as follows.

Case study : You have some informatrion in DB wich looks like the below 
Table name : Merchant
Columns : Merchantid(Number), Merchantname(varchar)
Sample Data : 10001    Best Buy
                         10002    Circuit city
                         10003     Macy's
                         10004     Toy's R us
                         10005      GK\nGB's

In application we are going to display this kind of data ...so assuming that we are able to get all these in array from DB and going to display like the below..


for ( int i = 0 ; left != null && i <> {
  tempObj = (Hashtable)left.get(i);
  leftMid += "'" + tempObj.get("marchantid").toString() + "'";
  leftMname +=  "'" + (tempObj.get("marchantname").toString()) + "'" ;
  if (i < (left.size()- 1) ){
  leftMid += ",";
  leftMname += ",";
  }
                      


Then sure the data will not show the rows 
10003     Macy's
10005      GK\nGB's

properly ...they may shown as 
10003     Macy
10005      GK GB
Most of the case it may throw error also in such cases just write small Java script function like the below and use this function to replace few charecters to show the coloumns as like in the DB

Java script function will be ...

 private String replaceSpecial(String input){
 if(input.indexOf("\\") != -1)
  input = input.replaceAll("\\\\", "\\\\\\\\");
 
 if(input.indexOf("'") != -1)
  input = input.replaceAll("'", "\\\\\'");
       return input;



And now change the above for loop code as below



for ( int i = 0 ; left != null && i <> {
  tempObj = (Hashtable)left.get(i);
  leftMid += "'" + tempObj.get("marchantid").toString() + "'";
  leftMname +=  "'" + replaceSpecial(tempObj.get("marchantname").toString()) + "'" ;
  if (i < (left.size()- 1) ){
  leftMid += ",";
  leftMname += ",";
  }
}


HTH ... 




0 comments to "How to replace esacape(\n \t) charecters and ' charecter in java"

Post a Comment

Who ever writes Inappropriate/Vulgar comments to context, generally want to be anonymous …So I hope U r not the one like that?
For lazy logs u can at least use Name/URL option which don’t even require any sign-in, good thing is that it can accept your lovely nick name also and URL is not mandatory too.
Thanks for your patience
~Krishna(I love "Transparency")
వీలయితే నాల్గు పోస్టులు ...కుదురితే ఒక కామెంటూ ...

Translate

Enter your email address:

Buffs ...

Visitors


hits counter
View My StatsCheck Google Page Rank

Add to Google Reader or Homepage

Bookmark and Share

Tags


Powered by WidgetsForFree

Archives