What is the isSameLength() method in D?
Overview
To get a variable’s length, we can use the .length property in D. However, this doesn’t offer the luxury of comparing different variables by length.
Therefore, the isSameLength() function is used. It compares the length of two variables and returns true or false. It returns true if both lengths are the same. Otherwise, it returns false.
Syntax
isSameLength(var_a,var_b)
var_a: This is the first variable whose length is to be checked.var_b: This is the second variable whose length is up for comparison.
Code
import std.stdio;import std.algorithm;//start main functionvoid main(){//declare variable to compare lengthint [] var_a = [1,2,3,4,5];int [] var_b = [6,7,8,9,10];string var_c = "This is the same";//comparing length of var_a and var_bif(isSameLength(var_a,var_b)){writeln("They are equal");}//comparing length of var_a and var_cif(isSameLength(var_a,var_c)){writeln("They are equal");}else{writeln("They are not equal");}}
Explanation
- Line 1–2: We import the necessary modules.
- Line 4: We start the
mainfunction. - Lines 6, 7, and 8: We declare new variables.
- Lines 11 and 12: We compare the length of
var_aandvar_busing theisSameLength()method inside anifcondition. - Lines 16–23: We compare the length of
var_aandvar_cusing theisSameLength()method inside anif,elsecondition.