Java String.replace() - replaces more than just the substring I specify? -


as per this codingbat problem trying following:

given string, if first or last chars 'x', return string without 'x' chars, , otherwise return string unchanged.

my code:

public string withoutx(string str) {     if (str.startswith("x")) {         str = str.replace(str.substring(0, 1), "");     }     if (str.endswith("x")) {         str = str.replace(str.substring(str.length()-1), "");     }     return str; } 

this code replaces x characters in string, rather first , last. why happen, , way solve it?

from sdk replace method:

returns new string resulting replacing all occurrences of oldchar in string newchar.

you can solve without replace:

public string withoutx(string str) {        if (str == null) {          return null;     }      if (str.startswith("x")) {         str = str.substring(1);     }     if (str.endswith("x")) {         str = str.substring(0, str.length()-1);     }      return str; } 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -