Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Removing ' from string.

 
Seshagiri Kamalakaran
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The strings contain more than one '(single quote). I want to replace it with \' (a back slash as escape sequence to render in javascript). The problem is the string can contain more than one '.
For example :
Paul's pet's name is jony.
The output shd be :
Paul\'s pet\'s name is jony.
Can any one help me in getting the logic to make this work?
Thanks
 
Marc Peabody
pie sneak
Sheriff
Posts: 4727
Mac Ruby VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that the String can contain more than one ' doesn't make much for a problem. What isn't working?
 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the replaceAll method of a String object:
 
Seshagiri Kamalakaran
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Yan for the solution... The thing is replaceAll method comes with java1.4 and at present we are using only java 1.3.. So using some string manipulations I have to do that...
Any other solution..?
 
Seshagiri Kamalakaran
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai I have found a solution .. but dont know whether this is efficient one..
public class StringExam
{
public static void main(String args[])
{
String original = "Paul's Pet's Name's is John's";
StringBuffer sb = new StringBuffer(original);
int i =0;
int j=0;
int cnt =0;
boolean flag = true;
do
{

char ch = original.charAt(i);
if(ch=='\'')
{
if(flag)
{
sb.replace(i,i+1,"\\'");
flag=false;
cnt++;
}
else
{
sb.replace(j,j+1,"\\'");
cnt++;
}
}

i++;
j=i+cnt;
}
while(i < original.length());

System.out.println("Original string: " + original);
System.out.println("After replaceAll string: " + sb.toString());
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic