#2298 How about...

SlimerDude Fri 6 Jun 2014

While I'm on a roll...

I was thinking that these methods could possibly be named better:

Str.replace()   --> Str.replaceAll()

List.findType() --> List.findAllOfType()

The first because only recently I read the docs for Str.replace()... all this time I assumed it only replaced the first occurrence! I was looking for a replaceAll() and hoped replace() would give me some clues. Indeed it did!

The second because I was never really clear on what it did.

An approach to updating APIs that I've been doing, is to use @Deprecated and @NoDoc on old methods at the same time. That way, the only people who notice the change are those who have already used the old methods.

(I gotta say, I love the whole @NoDoc thing. It's an inspired annotation!)

andy Mon 9 Jun 2014

Those are definitely clearer terms, but at this point, not sure renaming core methods is on the table ;)

SlimerDude Mon 9 Jun 2014

Yeah, I figured as much... that's why I mentioned the @Deprecated @NoDoc thing!

SlimerDude Thu 4 Aug 2016

Hi, given Str only has Str.replace(Str, Str), how about a Str.replaceFirst(Str, Str)?

There's a replaceFirst() in Java, which although it takes a regex, should be easy enough to escape - pseudo code:

Str replaceFirst(Str target, Str replacement) {
  regex := Regex.quote(target)
  return (this as java string).repaceFirst(regex, replacement)
}

SlimerDude Sat 4 Jan 2020

It's a bit long winded, but for those needing a replaceFirst() method:

static Str replaceFirst(Str str, Str from, Str to) {
    matcher := Regex.quote(from).matcher(str)
    return matcher.find ? matcher.replaceFirst(to) : str
}

Usage:

str := "Adding {___} to {___} gives a total sum of {___}."
num := 0
while (str.contains("{___}"))
    str = replaceFirst(str, "{___}", "${++num}")

echo(str)  // --> "Adding 1 to 2 gives a total sum of 3."

I dare say there's a more optimised method using StrBufs, but the above seems to work.

Login or Signup to reply.