dlang incompatible type error in checking string

Viewed 116

i have this code to check if string have j character

import std.stdio;

void main() {
    const string name = "john";
    for (int i = 0;i < name.length;i++) {
        if (name[i] == "j") {
           writeln("the name variable contain character j");
        }
    }
}

and then i get an error

Performing "debug" build using /Library/D/dmd/bin/dmd for x86_64.
learning ~master: building configuration "application"...
source/app.d(36,13): Error: incompatible types for `(name[cast(ulong)i]) == ("j")`: `immutable(char)` and `string`
/Library/D/dmd/bin/dmd failed with exit code 1.
2 Answers

"j" is a string. 'j' is a char. name[i] is also a char, so you are comparing a char to a string which gives the error.

I would use indexOf for achieving the same thing. The indexOf Dlang function searches for a character in a range.

Related