digitalmars.D.learn - get element index when using each!(x)
- dangbinghoo (13/13) Sep 16 2020 hi,
- JG (20/33) Sep 16 2020 Perhaps there are other ways, but you can use enumerate. For
- Paul Backus (6/16) Sep 16 2020 Worth knowing that the tuples you get from enumerate actually
- dangbinghoo (4/21) Sep 16 2020 thanks you! and thanks to JG.
- Jacob Carlborg (6/10) Sep 18 2020 It actually works out of the box for `each`:
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
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
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
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:thanks you! and thanks to JG. --------- binghooPerhaps 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
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









dangbinghoo <dangbinghoo google-mail.com> 