"strstr" D equivalent

Salih Dincer salihdb at hotmail.com
Fri Jul 29 13:31:27 UTC 2022


On Friday, 29 July 2022 at 11:23:55 UTC, pascal111 wrote:
> Is there an equivalent in D for C function "strstr" that return 
> the first occurrence of a given string within another string?
>
> https://en.cppreference.com/w/c/string/byte/strstr

https://dlang.org/library/std/string/index_of.html

I never want to break your fervour. But D has what you've been 
asking for a few days, or even better. Because we have a strong 
type like `immutable(char[])`. In summary, it only took me 1 
minute to compile the same code:

```d
// D 2.0.83
import std.string;
import std.stdio;

void find_str(string str, string substr)
{
     import std.typecons : No;
     auto pos = indexOf(str, substr, No.caseSensitive);
     if(pos) {
         writef("found the string '%s' in '%s' at position: %s\n", 
substr, str, pos);
     } else {
         writef("the string '%s' was not found in '%s'\n", substr, 
str);
     }
}

int main()
{
     string str = "one two three";
     find_str(str, "two");
     find_str(str, "");
     find_str(str, "nine");
     find_str(str, "n");

     return 0;
}
```

Search and you will definitely find it. If you can't find it, D 
handles this kind of thing anyway.

SDB at 79


More information about the Digitalmars-d-learn mailing list