Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: replacing subString

  1. #1
    Member
    Join Date
    Mar 2010
    Posts
    111
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default replacing subString

    package test852010;

    why this code sometimes work properly and sometimes doesn't? some times it doesn't remove "class" from the original String(l)
    public class test {
     
     
    	static String l = new String("href=http://en.wikipedia.org/wiki/Videoconferencing"+ " class="+"l");
     
    	public static void main(String[] args) {
     
    		if (l.contains("class=")){
    			l.replace("class=","");
    			System.out.println(l);
     
    		}
     
    		else 
    			System.out.println("No");
    	}
     
    }


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: replacing subString

    Strings in Java are immutable, so you must re-assign the value returned from l.replace() to l. Otherwise, l will never be changed.

    public class test {
     
     
    	static String l = new String("href=http://en.wikipedia.org/wiki/Videoconferencing"+ " class="+"l");
     
    	public static void main(String[] args) {
     
    		if (l.contains("class=")){
    			l = l.replace("class=","");
    			System.out.println(l);
     
    		}
     
    		else 
    			System.out.println("No");
    	}
     
    }

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    nasi (May 22nd, 2010)

Similar Threads

  1. dispose()'ing a JFrame and replacing it
    By musasabi in forum What's Wrong With My Code?
    Replies: 5
    Last Post: May 14th, 2010, 02:31 PM
  2. Substring function
    By bristol580 in forum Java SE APIs
    Replies: 2
    Last Post: November 12th, 2009, 11:29 AM
  3. First string is a substring of another
    By mgutierrez19 in forum What's Wrong With My Code?
    Replies: 13
    Last Post: October 21st, 2009, 10:35 PM
  4. Substring program, not working
    By Newoor in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 18th, 2009, 12:46 PM
  5. Replies: 5
    Last Post: January 30th, 2009, 09:31 PM