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 function
void main(){
//declare variable to compare length
int [] 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_b
if(isSameLength(var_a,var_b)){
writeln("They are equal");
}
//comparing length of var_a and var_c
if(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 main function.
  • Lines 6, 7, and 8: We declare new variables.
  • Lines 11 and 12: We compare the length of var_a and var_b using the isSameLength() method inside an if condition.
  • Lines 16–23: We compare the length of var_a and var_c using the isSameLength() method inside an if, else condition.

Free Resources