#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Location
    Phoenix, AZ
    Posts
    484
    Rep Power
    36

    Question Best way to replace string in substring?


    Java newbie here. I wish to open an html document and search for kewords which are to be replaced with other values.

    I checked out the String.replace() function which only works on characters. Is there another function I can use? I thought about trying to learn the regular expression functions to do it.

    Can anyone point me in the right direction?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Location
    Phoenix, AZ
    Posts
    484
    Rep Power
    36
    I figured it out, as follows:

    String htmlDoc = "<input name=cmName type=text value=__cmName__>";
    String oldString = "__cmName__";
    String newString = "Joel Nelson";

    int htmlLength = htmlDoc.length();
    int oldLength = oldString.length();
    int index = htmlDoc.indexOf(oldString.toString());

    if (index != -1) {
    htmlDoc = htmlDoc.substring (0, index) + newString.toString() + htmlDoc.substring (index + oldLength, htmlLength);
    }
  4. #3
  5. No Profile Picture
    Moderator =(8^(|)
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2002
    Location
    Sacramento, CA
    Posts
    1,710
    Rep Power
    14
    Well, if you have access to jdk 1.4, go ahead and learn the regular expression functions. They're not very difficult, and they're *extremely* useful.

    One suggestion that I might make to your code is to put it into a loop. That way all occurence get replaced, not just the first.

    PHP Code:
    String htmlDoc "<input name=cmName type=text value=__cmName__>";
    String find "__cmName__";
    String replace "Joel Nelson";

    int index = -1;

    while ( 
    index htmlDoc.indexOfoldString.toString() ) > -) {
        
    htmlDoc htmlDoc.substring0index ) + replace htmlDoc.substringindex find.length(), htmlDoc.length() );

    -james
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Location
    Phoenix, AZ
    Posts
    484
    Rep Power
    36
    Good point on the looping, bricker!

    I actually do know regular expressions, but via perl (my main language). I'm sure there are some differences in usage but they prolly work about the same. I'll check it out!
    There are only 10 kinds of people in this world. Those who understand binary, and those who don't!
  8. #5
  9. dont click here
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2002
    Posts
    409
    Rep Power
    13
    yah that works.. and you dont need toString() for all the strings it is default

IMN logo majestic logo threadwatch logo seochat tools logo