File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Regarding remove word in a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regarding remove word in a string" Watch "Regarding remove word in a string" New topic

Regarding remove word in a string

santhosh kumar vk
Ranch Hand

Joined: Aug 25, 2009
Posts: 151

how to remove a word to another word from string

for example

i have a string like String s= "<html><body>this is test</body></html>

in the above string i have to remove the starting <body> tag to ending</ body> tag in between the value will come dynamically,the out put should be s="<html></html>"

can you please help me

K Amit Gupta

Joined: Feb 22, 2011
Posts: 4

You can use Regex in java to manuplate these kind of thing...
I have one programme.. which can help you if you don't want to google Regrx.
but this programme is for one occurance. you can run it in a loop....

i think you must try with Regrx... that will really help...

class Demo{
public static void main(String args[]){
String str="<html><body>this is test</body></html>";
String str1="<body>";
String str2="</body>";
Demo d1=new Demo();

int startpara=d1.startindex(str,str1);
int endpara=d1.endindex(str,str2);

String finalString=str.substring(0,startpara)+str.substring(endpara+str2.length(),str.length());



public int startindex(String str, String str1){
int indexstart= str.indexOf(str1,0);
return indexstart;

public int endindex(String str,String str2){
int endindex= str.indexOf(str2,0);
return endindex;

Riaan Nel
Ranch Hand

Joined: Apr 23, 2009
Posts: 160

I'd look at using the substring() method with the index of "<html>" and "</html>".

On a side note, do you always want to get a String with only the opening and closing HTML tags?

"The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man." - George Bernard Shaw
santhosh kumar vk
Ranch Hand

Joined: Aug 25, 2009
Posts: 151

Thank you for your reply,can you tell me how to do using regular expression.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11952

<pedant mode>
You cannot remove a word from a string. Strings are immutable. All you can do is create a new string formed how you want.
</pedant mode>

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
santhosh kumar vk
Ranch Hand

Joined: Aug 25, 2009
Posts: 151
i need new string,just i have to replace as a "" in that string
I agree. Here's the link:
subject: Regarding remove word in a string
It's not a secret anymore!