reading file byLine

deed via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 5 07:44:18 PDT 2015


On Saturday, 5 September 2015 at 12:41:37 UTC, Namal wrote:
> Thx guys. Now I try out the split function. I read the file as 
> a single string?
>
> auto arr = split(cast(string)read(filename),",");
>
> where the file has "A", "B", "C"
>
> and I get the output ["\"A\"", " \"B\"", " \"C\"\n"]
>
> I can understand that read functions reads the endl but what 
> does it with the quotation marks? how can I modify read so I 
> get just ["A", "B", "C"]

'\' is the escape character and is used to disambiguate start or 
end of string (") and a quotation mark within the string (\"), 
the same way as "\n" means newline and not '\' 'n', which would 
have been "\\n".

So what you have is [`"A"`, ` "B"`, ` "C"\n`], if you use ` for 
start\stop of string. You say you want ["A", "B", "C"], so you 
need to remove whitespace. You can do that with std.string.strip. 
Assuming you also want to remove the quotation marks present in 
the file, one solution is to use std.string.chomp and 
std.string.chompPrefix, for example:

string s = cast(string) read(filename);
s.split(",")
  .map!strip
  .map!(s => chomp(s, "\"")
  .map!(s => chompPrefix(s, "\"")
  .writeln
  ;


More information about the Digitalmars-d-learn mailing list