• (cs)

    This looks oddly familiar. We have a class by the same name that also reinvents the wheel.

  • QJo (unregistered)

    I used to maintain a codebase wherein we had a "StringUtils" class, but this was mainly to allow us to conveniently catch null strings. Also, the string manipulation routines in java 1.3 was limited compared to more recent versions. Hence it was necessary.

    Note the "toRepalce" in the codebase. Dyseliaxa needs to be rmevoeed from all cdboeases.

  • (cs)

    Well, I guess Freemarker, MVEP or Velocity were very hard to understand for this so called architect.

  • RFoxMich (unregistered)

    Re the comment in the source...1.

  • Lothar (unregistered)

    String.replaceAll expects a regular expression, so the given helper method is not a real reinvention of the wheel.

  • (cs)

    Repalce.

    Also... who the hell uses the indefinite article at the start of variable/parameter names? Baffling.

  • Robyrt (unregistered)

    So replaceAll("","","Bob") returns "Bob"? That's pretty Zen.

  • Erik (unregistered) in reply to Lothar

    String.replaceAll do expect a regexp, and as such is the wrong function for when you are replacing literal substrings. The function you want is String.replace.

  • (cs)

    So what's the recommended way to do this?

    String.replaceAll wants a regex => does not fit

    String.replace only replaces the first => does not fit

    Calling replace multiple times? Would replace the searched string in the replacement string => does not work

  • (cs) in reply to Strolskon
    Strolskon:
    String.replace only replaces the first => does not fit
    That's not what the API doc says.
  • (cs) in reply to Strolskon

    String.replace replaces all instances of a Char or CharSequence (Strings implement CharSequence). String.replaceFirst replaces only the first instance.

  • Mikael (unregistered) in reply to Strolskon
    So what's the recommended way to do this?
    Pattern.compile(regex, LITERAL).matcher(str).replaceAll(repl)
  • Anon (unregistered) in reply to Mikael

    The recommended way to replace all instance of a literal substring with a different literal substring is:

    targetString.replace(toReplace, replacemnt);

    No patterns/matchers/regex involved.

  • EvilSnack (unregistered)

    Just to get the obligatory posts out of the way:

    1. TRWTF is Java.

    2. I'm Philip.

    3. I'm Philip, and so's my wife!

    Captcha letatio: "The mayor has denied rumors that he received letatio from his secretary."

  • Mikael (unregistered) in reply to Anon
    Anon:
    The recommended way to replace all instance of a literal substring with a different literal substring is:

    targetString.replace(toReplace, replacemnt);

    No patterns/matchers/regex involved.

        public String replace(CharSequence target, CharSequence replacement) {
            return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                    this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
        }
    

    http://hg.openjdk.java.net/jdk7u/jdk7u40/jdk/file/ed809dc4f278/src/share/classes/java/lang/String.java row 2179

  • zennnnnn (unregistered) in reply to Robyrt
    Robyrt:
    So replaceAll("","","Bob") returns "Bob"? That's pretty Zen.

    Zen would be replaceAll("abc", "", "Bo" returns "BoaBobBocBo"

  • Pock Suppet (unregistered)
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }

    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!

    A Yoda-style

    = null anOldString =
    would be perfectly acceptable, however.
  • Chaarmann (unregistered)

    I can't see a WTF here. The replace method could be written with less code lines and not allow empty string argument, but it seems to work fine.

    Sometimes you must use old java versions like JDK1.3, especially if you are programming for embedded systems where you are limited in memory, which means: You cannot upgrade to a newer Java version, and you can add a method, but not include an additional library like the jakarta-commons-*.jar!

    In JDK1.3 there is only a single replace-method available: replace(char oldChar, char newChar)

  • foo (unregistered) in reply to Pock Suppet
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!

    A Yoda-style

    = null anOldString =
    would be perfectly acceptable, however.
      return null; unless (null != aReceiver);
    
  • Andrew (unregistered) in reply to Pock Suppet
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug, but
    null = aReceiver
    is a compiler error. Grammatical word order be damned.
  • foo (unregistered) in reply to Andrew
    Andrew:
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug
    Which modern compiler doesn't warn about this (when used in a conditional).
  • JC (unregistered) in reply to Andrew
    Andrew:
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug, but
    null = aReceiver
    is a compiler error. Grammatical word order be damned.

    I don't know about Java, but in C# if (aReceiver = null) { stuff }

    would be a compiler error as the expression doesn't result in a boolean.

  • EuroGuy (unregistered) in reply to Andrew
    Andrew:
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug, but
    null = aReceiver
    is a compiler error. Grammatical word order be damned.
    Any programmer who is pedentic enough to use the Yoda style, is probably also professional enough not to confuse = and ==.

    So the people who use "normal" style are the suspicious ones. However, the Yoda programmers are unsufferable know-it-alls. I prefer the former types as my coworkers.

  • (cs) in reply to Andrew
    Andrew:
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug, but
    null = aReceiver
    is a compiler error. Grammatical word order be damned.

    Much nicer in C++:

    SomeStringClassThing* aReciever;
    if (!aReciever || (!anOldString || !aNewString))
    {
      return aReceiver;
    }
    

    No bugs or compiler errors.

  • (cs)

    Unicorns and Rainbows! Who cares about anything else? Quick... someone call the BATFE!

    Edit: Clicking [Expand Full Text] then clicking on "orientation" works in the comments section as well... didn't expect that... Trippy...

  • Tasty (unregistered) in reply to foo
    foo:
    Andrew:
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug
    Which modern compiler doesn't warn about this (when used in a conditional).

    Which modern compiler doesn't warn about 1,000 things at a time? Why search for a needle in a haystack when you can just find the real errors?

  • Tasty (unregistered) in reply to EuroGuy
    EuroGuy:
    Andrew:
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug, but
    null = aReceiver
    is a compiler error. Grammatical word order be damned.
    Any programmer who is pedentic enough to use the Yoda style, is probably also professional enough not to confuse = and ==.

    So the people who use "normal" style are the suspicious ones. However, the Yoda programmers are unsufferable know-it-alls. I prefer the former types as my coworkers.

    Yoda followed Altaic grammar, topic-comment-verb, not object-verb-subject. It's a hidden refernce to Japanese martial artists. Now, this is being a know-it-all!

  • Bring Back TopCod3r (unregistered) in reply to Tasty
    Tasty:
    foo:
    Andrew:
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug
    Which modern compiler doesn't warn about this (when used in a conditional).

    Which modern compiler doesn't warn about 1,000 things at a time? Why search for a needle in a haystack when you can just find the real errors?

    Nice trolling there.

  • Evan (unregistered) in reply to JC
    Erik:
    String.replaceAll do expect a regexp, and as such is the wrong function for when you are replacing literal substrings. The function you want is String.replace.
    Remy Porter:
    String.replace replaces all instances of a Char or CharSequence (Strings implement CharSequence). String.replaceFirst replaces only the first instance.
    That is a terrible naming scheme.
    JC:
    I don't know about Java, but in C# if (aReceiver = null) { stuff }

    would be a compiler error as the expression doesn't result in a boolean.

    Same in Java, and similar in C and C++ because you're compiling with -Wall and compiling cleanly. Aren't you?

    Though there is still one case where the C/C++ warning does a better job:

    bool a, b;
    ...
    if (a = b) { ... }

    is, without checking, I think legal C# and Java.

  • trtrwtf (unregistered) in reply to EuroGuy
    EuroGuy:
    Any programmer who is pedentic enough to use the Yoda style, is probably also professional enough not to confuse = and ==.

    And experienced enough to have moderate RSI. Typos do happen, and when your hands hurt, they happen more.

    CAPTCHA: incassum - incassum not here, I'll leave the side door open.

  • C-Derb (unregistered) in reply to Evan
    Evan:
    Though there is still one case where the C/C++ warning does a better job:
    bool a, b;
    ...
    if (a = b) { ... }
    is, without checking, I think legal C# and Java.
    This ignores the original complaint, which was
    Pock Suppet:
    Can we kill this constant == variable pattern, yet?
    Personally, I think that practice is silly and weird to read, and I would be fine with never seeing it again. Remembering to put your constant on the left side of the comparison operator takes as much effort as remembering to use the comparison operator instead of the assignment operator. So why not make the code more readable?
  • (cs) in reply to Evan
    Evan:
    Remy Porter:
    String.replace replaces all instances of a Char or CharSequence (Strings implement CharSequence). String.replaceFirst replaces only the first instance.
    That is a terrible naming scheme.

    No it's not.

    Having "replace" manage to only replace the first instance is not intuitive at all.

    What if someone asked you to buy a dozen eggs, but replace broken eggs, and you only replaced the first broken egg?

    replace"All" should be implied.

    replace"First/Last/Count" should be a specification.

  • (cs) in reply to C-Derb
    C-Derb:
    Evan:
    Though there is still one case where the C/C++ warning does a better job:
    bool a, b;
    ...
    if (a = b) { ... }
    is, without checking, I think legal C# and Java.
    This ignores the original complaint, which was
    Pock Suppet:
    Can we kill this constant == variable pattern, yet?
    Personally, I think that practice is silly and weird to read, and I would be fine with never seeing it again. Remembering to put your constant on the left side of the comparison operator takes as much effort as remembering to use the comparison operator instead of the assignment operator. So why not make the code more readable?

    In Java, doing something like:

    if ("TestString".equals(variable)) { : : etc.

    saves on having to test whether variable is null. Do it the other way round and you have to try-catch NullPointerExceptions.

  • Jeremy (unregistered) in reply to xaade
    xaade:
    Evan:
    Remy Porter:
    String.replace replaces all instances of a Char or CharSequence (Strings implement CharSequence). String.replaceFirst replaces only the first instance.
    That is a terrible naming scheme.

    No it's not.

    Having "replace" manage to only replace the first instance is not intuitive at all.

    What if someone asked you to buy a dozen eggs, but replace broken eggs, and you only replaced the first broken egg?

    replace"All" should be implied.

    replace"First/Last/Count" should be a specification.

    Absolutely.

  • (cs) in reply to C-Derb
    C-Derb:
    Evan:
    Though there is still one case where the C/C++ warning does a better job:
    bool a, b;
    ...
    if (a = b) { ... }
    is, without checking, I think legal C# and Java.
    This ignores the original complaint, which was
    Pock Suppet:
    Can we kill this constant == variable pattern, yet?
    Personally, I think that practice is silly and weird to read, and I would be fine with never seeing it again. Remembering to put your constant on the left side of the comparison operator takes as much effort as remembering to use the comparison operator instead of the assignment operator. So why not make the code more readable?

    Not really.

    Using a compiler that only accepts boolean values for the result of an if statement is the best option.

    Continuing to place the constant on the left in such a language is TRWTF.

  • (cs) in reply to Tasty
    Tasty:
    foo:
    Andrew:
    Pock Suppet:
    if (null == aReceiver) {
      return null;
    }
    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }
    Can we kill this constant == variable pattern yet? You're not testing the value of null or 3 or PI; you're testing the variable. Object-verb-subject order doesn't grammatically match very many programming languages (or many spoken languages, for that matter), so stop using it! Nao!
    No, we can't stop doing this. There is less room for sneaky failures, because leaving out an = means
    aReceiver = null
    might be a bug
    Which modern compiler doesn't warn about this (when used in a conditional).

    Which modern compiler doesn't warn about 1,000 things at a time? Why search for a needle in a haystack when you can just find the real errors?

    If your compiler gives you 1000 warnings I rather think you need to go back to Programming 101. Leaving warnings unattended is bone-headed.

  • (cs) in reply to Matt Westwood
    Matt Westwood:
    C-Derb:
    Evan:
    Though there is still one case where the C/C++ warning does a better job:
    bool a, b;
    ...
    if (a = b) { ... }
    is, without checking, I think legal C# and Java.
    This ignores the original complaint, which was
    Pock Suppet:
    Can we kill this constant == variable pattern, yet?
    Personally, I think that practice is silly and weird to read, and I would be fine with never seeing it again. Remembering to put your constant on the left side of the comparison operator takes as much effort as remembering to use the comparison operator instead of the assignment operator. So why not make the code more readable?

    In Java, doing something like:

    if ("TestString".equals(variable)) { : : etc.

    saves on having to test whether variable is null. Do it the other way round and you have to try-catch NullPointerExceptions.

    Or you could do what I did and make an extension method on object that checks for null.

    Then you just have variable.EqualsNullSafe("TestString"). And if variable is null it returns false.

  • (cs) in reply to Matt Westwood
    Matt Westwood:
    Tasty:
    Which modern compiler doesn't warn about 1,000 things at a time? Why search for a needle in a haystack when you can just find the real errors?

    If your compiler gives you 1000 warnings I rather think you need to go back to Programming 101. Leaving warnings unattended is bone-headed.

    Beware the Ides of March.

  • Paul Neumann (unregistered)
    String aReceiver, toReplace, replaceWith;
    
    aReceiver = "Useful text. /*Remove me*/ More usefulText.";
    toReplace = "/*Remove me*/ ";
    replaceWith = null;
    
    String result = FunctionLibrary.replaceAll(aReceiver, toReplace, replaceWith);
    Assert.equal(null, result);
  • gnasher729 (unregistered) in reply to eViLegion
    eViLegion:
    [Much nicer in C++:
    SomeStringClassThing* aReciever;
    if (!aReciever || (!anOldString || !aNewString))
    {
      return aReceiver;
    }
    

    No bugs or compiler errors.

    I once lost a week of my life because someone who was assumed to be very clever replaced

    if (ptr != NULL)

    with

    if (! ptr)

    without checking the code, without doing a code review, in a place where it caused the maximum possible damage. The reason for the change was that he felt the second way looked more clever. I could have killed him. I should have killed him. Note that unlike the "=" vs. "==" confusion, the compiler has absolutely no chance to give a warning, just like it can't give a warning if you write "ptr == NULL" instead of "ptr != NULL".

  • gnasher729 (unregistered) in reply to Tasty
    Tasty:
    Which modern compiler doesn't warn about 1,000 things at a time? Why search for a needle in a haystack when you can just find the real errors?

    Mine doesn't. Because I've turned on the "warning = errors" settings, so any warning gets fixed immediately. Actually, I'd estimate that more than half the warnings turn out to be logic errors which would have been much harder to find if I didn't leave it to the compiler.

  • Paul Neumann (unregistered) in reply to C-Derb
    C-Derb:
    Evan:
    Though there is still one case where the C/C++ warning does a better job:
    bool a, b;
    ...
    if (a = b) { ... }
    is, without checking, I think legal C# and Java.
    This ignores the original complaint, which was
    Pock Suppet:
    Can we kill this constant == variable pattern, yet?
    Personally, I think that practice is silly and weird to read, and I would be fine with never seeing it again. Remembering to put your constant on the left side of the comparison operator takes as much effort as remembering to use the comparison operator instead of the assignment operator. So why not make the code more readable?
    It is exactly as I expect: "Expected == Actual" which is what I think when I am making an assertion.
  • trtrwtf (unregistered) in reply to eViLegion
    eViLegion:
    Matt Westwood:
    Tasty:
    Which modern compiler doesn't warn about 1,000 things at a time? Why search for a needle in a haystack when you can just find the real errors?

    If your compiler gives you 1000 warnings I rather think you need to go back to Programming 101. Leaving warnings unattended is bone-headed.

    Beware the IDEs of March.

    FTFY

  • NullIsNotAnObjectBro (unregistered) in reply to xaade

    So you did an extension method on object that checks for null so you can call object methods on null references in Java ?

    And what you was smoking while doing that ? I want some of your good shit.

    It turns null to an object just with a couple of puffs.

    null is not an Object, is just a special kind of weird type who can't be used to declare or cast anything to it, it only can be referenced.

  • (cs) in reply to xaade
    xaade:
    Matt Westwood:
    In Java, doing something like: if ("TestString".equals(variable)) { : : etc.

    saves on having to test whether variable is null. Do it the other way round and you have to try-catch NullPointerExceptions.

    Or you could do what I did and make an extension method on object that checks for null.

    Then you just have variable.EqualsNullSafe("TestString"). And if variable is null it returns false.

    Matt Westwood is right here.
    If you have a constant TEST_VALUE which is statically defined somewhere, you should always do if(TEST_VALUE.equals(input)){}

    If you instead call the equals() method of the input object, you must first check it for non-null like this: if(input != null && input.equals(TEST_VALUE)){}

    doing it in the right order saves the null check.
    The guy who talked about overloading object to handle this is a troll who is trying to create Null Pointer Errors (if 'input' is null, it doesn't have that overloaded method anyway, it's NULL!!).

  • SteveThePirate (unregistered) in reply to xaade
    xaade:
    Matt Westwood:
    C-Derb:
    Evan:
    Though there is still one case where the C/C++ warning does a better job:
    bool a, b;
    ...
    if (a = b) { ... }
    is, without checking, I think legal C# and Java.
    This ignores the original complaint, which was
    Pock Suppet:
    Can we kill this constant == variable pattern, yet?
    Personally, I think that practice is silly and weird to read, and I would be fine with never seeing it again. Remembering to put your constant on the left side of the comparison operator takes as much effort as remembering to use the comparison operator instead of the assignment operator. So why not make the code more readable?

    In Java, doing something like:

    if ("TestString".equals(variable)) { : : etc.

    saves on having to test whether variable is null. Do it the other way round and you have to try-catch NullPointerExceptions.

    Or you could do what I did and make an extension method on object that checks for null.

    Then you just have variable.EqualsNullSafe("TestString"). And if variable is null it returns false.

    That doesn't make since. If variable is null it is not an object and therefore that method doesn't exist for it.

  • JC (unregistered) in reply to SteveThePirate
    SteveThePirate:
    That doesn't make since. If variable is null it is not an object and therefore that method doesn't exist for it.

    You can do that with extension methods in C# as he says. This runs and prints 'Object is null'

    void Main()
    {
    	object obj = null;
    	
    	if (obj.IsNull())
    	{
    		Console.WriteLine("Object is null");
    	}
    }
    
    public static class Extensions
    {
    	public static bool IsNull(this object o)
    	{
    		return o == null;		
    	}
    }
    
  • C-Derb (unregistered) in reply to JC
    JC:
    SteveThePirate:
    That doesn't make since. If variable is null it is not an object and therefore that method doesn't exist for it.

    You can do that with extension methods in C# as he says. This runs and prints 'Object is null'

    void Main()
    {
    	object obj = null;
    	
    	if (obj.IsNull())
    	{
    		Console.WriteLine("Object is null");
    	}
    }
    
    public static class Extensions
    {
    	public static bool IsNull(this object o)
    	{
    		return o == null;		
    	}
    }
    

    Didn't you mean

    return null == o;
    See how stupid that notation is? Even in a debate about the merits of that pattern, it is just simply more natural to write myVar == conditionalValue.

    Debate over.

  • (cs) in reply to Tasty
    Tasty:
    Yoda followed Altaic grammar, topic-comment-verb, not object-verb-subject. It's a hidden refernce to Japanese martial artists. Now, this is being a know-it-all this being a know-it-all is!
    FTFY :)
  • (cs) in reply to C-Derb
    C-Derb:
    Pock Suppet:
    Can we kill this constant == variable pattern, yet?
    Personally, I think that practice is silly and weird to read, and I would be fine with never seeing it again. Remembering to put your constant on the left side of the comparison operator takes as much effort as remembering to use the comparison operator instead of the assignment operator. So why not make the code more readable?
    People who get thrown by the order of arguments to a commutative operator are TRWTF.

Leave a comment on “Stringing a Replacement”

Log In or post as a guest

Replying to comment #412334:

« Return to Article