What is the indexOf() method in D programming?

The indexOf() method

D language has a built-in method named indexOf(). This method is used to return the index of a particular substring in a character array, i.e., char[].

Note: The method indexOf()only works on char[] arrays.

Each member of an array has an index value by which it can be accessed. This index will point to the particular element in the array, thus making it possible for the element to be returned using the index value.

Implementing the char[] array

We get a character array by casting a string to an array. We do this by using the .dup array property and copying the contents of the string as a single character array or doing a type conversion, as in the following:


char [] hold = "Hold this values".dup

Now, we can now use the indexOf() on the char variable hold.

Syntax


indexOf(array_char, sub_char,case_nature)

Parameters

  • array_char: This is the character array that serves as the range with the sub_char parameter.

  • sub_char: The sub-character whose position in array_char is to be returned.

  • case_nature: This is where we specify if the method should be case sensitive or not, using the CaseSensitive property of character.

Return value

The indexOf() method will return an integer value, which is the index of the first occurrence of the sub-char. If the sub-char in question is a set of characters like “lo” from “hello”, it will return the index of the first character in this set. In this case, it will be the index of “l”, which is 3 in “hello”.

Example

A simple variation of indexOf() is lastIndexOf(). It is almost exactly the same as indexOf(), except that it returns the index of the last occurrence of the character in the character array. For example, for the word shearer, the lastIndexOf() for e will be 6 instead of 3, which would have been the case if we had used the indexOf() method.

Code

In the code below, the index of a sub-char in a char variable is checked and returned.

import std.stdio;
import std.string;
void main() {
char[] sub_char = "Educative Edpresso".dup;
writeln("indexOf of \"tive\" in Educative Edpresso is: ",
indexOf(sub_char,"tive"));
writeln("lastIndexOf of all cases of \"e\" in \"Educative Edpresso\" is: " ,
lastIndexOf(sub_char, "e", CaseSensitive.no));
writeln("lastIndexOf of uppercase \"E\" in \"Educative Edpresso\" is: " ,
lastIndexOf(sub_char, "E", CaseSensitive.yes));
}

Explanation

  • Lines 1-2: We import the necessary packages.

  • Line 4: We start the main() function.

  • Line 5: We define a character array using the .dup property to convert the string value.

  • Lines 7-13: We use the indexOf() and lastIndexOf() methods to get the index of sub-characters in the character array.

Free Resources