aspose file tools*
The moose likes Java in General and the fly likes Can you simulate String.replace(...) & String.contains(...) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can you simulate String.replace(...) & String.contains(...)" Watch "Can you simulate String.replace(...) & String.contains(...)" New topic
Author

Can you simulate String.replace(...) & String.contains(...)

Majid Al-Fifi
Ranch Hand

Joined: Aug 22, 2006
Posts: 45
Hi All,

As you know jdk1.5 String class provides
*** replace(String,String) and
*** contains(String)

I have developed an app that uses those methods to discover that I need to compile my app using jdk1.4 because of some restrictions on the production environment.

I am thinking of making MyStringUtil.java
and make the method as follows:

public static String replace(String str, String s1, String s2)
{
//find all s1's in str and replace them with s2's
//return str
}

Does anyone have code for an algorithm that does their job exactly.
Is there a better alternative?

Thanks..
Majid
[ August 29, 2006: Message edited by: Majid Al-Fifi ]

SCJP1.4, SCWCD1.4
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

*** replace(String,String)

You could write a regular expression and use String.replaceFirst()

*** contains(String)

and again you could write a regular expression and use String.matches() .

The detail of the regular expressions to use depends on the characters to be replaced/matched.


Retired horse trader.
 Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
For the contains() method, I would just do it the way Sun did: (That method has always seemed like a waste of space to me.) As for replace(), I would use replaceAll() behind the scenes: Having to pre-process the strings seems inefficient, but (for longer target strings, at least) that will be offset by the fact that the regex package will use a Boyer-Moore algorithm to do the searching.
Majid Al-Fifi
Ranch Hand

Joined: Aug 22, 2006
Posts: 45
Thanks guys,

I have used used the two methods Alan provided and everything is fine.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can you simulate String.replace(...) & String.contains(...)