On 2009-05-14 11:06:44 -0400, Andrei Alexandrescu <[email protected]> said:

auto before = str[0 .. find(str, something)];

Hum, wouldn't this be more intuitive:

        auto before = str.before(str.find(something));

That could work by having "find" return a range over the searched string. At first glance having find(str, "def") returning "def" sounds silly and unhelpful, but since the returned "def" is a range over the original, you can do a lot of interesting things with it, such as:

        auto str = "abcdefghi";
        auto strSlice = str.find("def"); // strSlice == "def"
        auto strBefore = str.before(slice); // strBefore == "abc"
        auto strAfter = str.after(slice); // strAfter == "ghi"

An interesting thing is that it makes a lot of sense with a regex argument in find:

        auto str = "abcdefghi";
        auto strSlice = str.find(regex("c.*g")); // strSlice = "cdefg"
        auto strBefore = str.before(strSlice); // strBefore = "ab"
        auto strAfter = str.after(strSlice); // strAfter = "hi"

And you can modify the result in place:

        auto str = "hello world";
        str.find("world")[] = "range";
        assert(str == "hello range");

... although that's somewhat limited since slice[] = x can't change the number of characters in the slice.

The "not found" result would be the end of the string: str[$..$].

Getting the position of the found string would be done like this:

        auto str = "abcdefhij";
        auto pos = str.before(str.find("def)).length; // pos == 3

But I guess having "findPos" or "indexOf" for that would be more readable.


--
Michel Fortin
[email protected]
http://michelf.com/

Reply via email to