File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Removing ' from string. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Removing Watch "Removing New topic
Author

Removing ' from string.

Seshagiri Kamalakaran
Greenhorn

Joined: Feb 12, 2004
Posts: 4
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

Joined: Feb 05, 2003
Posts: 4727

The fact that the String can contain more than one ' doesn't make much for a problem. What isn't working?


A good workman is known by his tools.
Adrian Yan
Ranch Hand

Joined: Oct 02, 2000
Posts: 688
Use the replaceAll method of a String object:
Seshagiri Kamalakaran
Greenhorn

Joined: Feb 12, 2004
Posts: 4
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

Joined: Feb 12, 2004
Posts: 4
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());
}
}
 
Don't get me started about those stupid light bulbs.
 
subject: Removing ' from string.