reading file byLine

deed via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 12 20:20:28 PDT 2015


On Saturday, 12 September 2015 at 12:51:04 UTC, Namal wrote:
> Anyway, there is no .reverse for strings I guess, what is the 
> way to completely reverse a string in D?

What do you want to do? Do you want to keep your data in original 
order, but get a reversed view of it for something, or do you 
actually want to reverse your original array?

You can use `retro` to simply read your array backwards, i.e.:
string s = "Some text";
s.retro.writeln;           // `txet emoS`
s.writeln;                 // `Some text`
s.retro.find("e");         // `Some te` (Surprising to me. Error? 
2.067.1)
s.retro.until("e").writeln;// `tx`
s.find("e");               // `Some`

The string is still kept in original order, but `retro` returns a 
range reading the array backwards. If you want to store a 
reversed string in memory, that's possible too, of course. One 
way of doing it, is to convert your retro range to a string:

s = s.retro.to!string;
s.writeln;                 // `txet emoS`

This will allocate new memory for the reversed copy and assign it 
to `s`.
Reverse is an algorithm that swaps values at different indices 
and since `string` is an alias for `const(char)[]`, it's not 
allowed. It means that each element of the array is const, so you 
cannot mutate any elements, but you can append or remove elements 
or assign the slice to view another part of the string or some 
other string. Hence, a `s.reverse` will give you an error. If you 
use `char[]` instead of `const(char)[]` you can use reverse and 
reuse the same memory for the reversed `char[]`. To illustrate:

char[] t = ['a', 'b', 'c'];
std.algorithm.reverse(t);
t.writeln;                 // `cba`

// s[0] = s[$-1];          // Error, cannot mutate const elements
auto r = s.retro;
s.length = 0;
r.each!(e => s ~= e);
s.writeln;                 // s has the reversed string, obtained 
through
                            // a temporary range object, setting 
length to
                            // zero and appending the elements 
from the
                            // range, which is allowed for 
const(char)[]


More information about the Digitalmars-d-learn mailing list