www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - get element index when using each!(x)

reply dangbinghoo <dangbinghoo google-mail.com> writes:
hi,

is there any way to get the index for an element when iteration 
using each!(x)?

  I know I can do this using foreach statement, but I prefer using 
the each template.

-----------
string s = "hello";
foreach(i, c; s) {
}
----------

how can I get to ?


Thanks!

binghoo dang
Sep 16 2020
parent reply JG <someone somewhere.com> writes:
On Thursday, 17 September 2020 at 00:51:54 UTC, dangbinghoo wrote:
 hi,

 is there any way to get the index for an element when iteration 
 using each!(x)?

  I know I can do this using foreach statement, but I prefer 
 using the each template.

 -----------
 string s = "hello";
 foreach(i, c; s) {
 }
 ----------

 how can I get to ?


 Thanks!

 binghoo dang
Perhaps there are other ways, but you can use enumerate. For example ----------- import std.algorithm; import std.range; import std.stdio; void main() { string s = "hello"; s.enumerate.each!(x=>writeln(x[0],":",x[1])); } ----------- Produces ----------- 0:h 1:e 2:l 3:l 4:o -----------
Sep 16 2020
parent reply Paul Backus <snarwin gmail.com> writes:
On Thursday, 17 September 2020 at 03:14:08 UTC, JG wrote:
 Perhaps there are other ways, but you can use enumerate. For 
 example
 -----------
 import std.algorithm;
 import std.range;
 import std.stdio;
 void main() {
  string s = "hello";
  s.enumerate.each!(x=>writeln(x[0],":",x[1]));
 }
Worth knowing that the tuples you get from enumerate actually have named members, so you can write: s.enumerate.each!(x => writeln(x.index, ":", x.value)); Documentation: http://dpldocs.info/experimental-docs/std.range.enumerate.html
Sep 16 2020
next sibling parent dangbinghoo <dangbinghoo google-mail.com> writes:
On Thursday, 17 September 2020 at 03:16:42 UTC, Paul Backus wrote:
 On Thursday, 17 September 2020 at 03:14:08 UTC, JG wrote:
 Perhaps there are other ways, but you can use enumerate. For 
 example
 -----------
 import std.algorithm;
 import std.range;
 import std.stdio;
 void main() {
  string s = "hello";
  s.enumerate.each!(x=>writeln(x[0],":",x[1]));
 }
Worth knowing that the tuples you get from enumerate actually have named members, so you can write: s.enumerate.each!(x => writeln(x.index, ":", x.value)); Documentation: http://dpldocs.info/experimental-docs/std.range.enumerate.html
thanks you! and thanks to JG. --------- binghoo
Sep 16 2020
prev sibling parent Jacob Carlborg <doob me.com> writes:
On 2020-09-17 05:16, Paul Backus wrote:

 Worth knowing that the tuples you get from enumerate actually have named 
 members, so you can write:
 
      s.enumerate.each!(x => writeln(x.index, ":", x.value));
It actually works out of the box for `each`: s.each!((index, value) => writeln(index, ":", value)); https://dlang.org/phobos/std_algorithm_iteration.html#.each -- /Jacob Carlborg
Sep 18 2020