www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - What is the best way to iterate over string chars?

reply "Cooler" <kulkin hotbox.ru> writes:
Example1:
for(size_t i; i < s.length; ++i){
   // do something with s[i]
}

Example2:
foreach(i; 0 .. s.length){
   // do something with s[i]
}

Example3:
foreach(i, c; s){
   // do something with c and i
}

What is the preferable way for portability, performance, compiler?
Feb 06 2014
parent "Adam D. Ruppe" <destructionator gmail.com> writes:
On Thursday, 6 February 2014 at 18:50:28 UTC, Cooler wrote:
 Example3:
 foreach(i, c; s){
   // do something with c and i
 }
this is the best. You can also specific c to be char or wchar or dchar specifically if you want it do do some UTF decoding for you. (char is the default - note that this will send you each byte of a multi-byte sequence. dchar on the other hand will automatically combine those)
Feb 06 2014