DEV Community

Jesse Phillips
Jesse Phillips

Posted on

Parsing a String in D

Parsing a String

First thing is first we want to read in a file. I won't be writing full compiling examples as I'm usually doing this on my phone. However, in general any examples can be pasted directly into a main function because D has nested everything.

void main() {
   import std.file;
   auto data = readText("filename.ext");
}
Enter fullscreen mode Exit fullscreen mode

readText reads the entire file into memory. Usually not a bad start but could be a problem with very large files. D also utilizes immutable strings, so techniques I'm showing generally do not use additional memory.

Matching Beginning or End

startsWith

Sometimes all that is needed is a check if the beginning or end matches a value.

import std.algorithm;
auto data = "word word"
assert(data.startsWith("word"));
assert(data.endsWith("word"));
assert(data.skipOver("word"));
assert(data == " word");
Enter fullscreen mode Exit fullscreen mode

skipOver will not only identify if the string is found at the beginning, but also move data past the string.

Removing Whitespace

strip

import std.string;
auto data = " str ";
assert(data.strip == "str");
assert(data.stripLeft == " str");
assert(data.stripRight == "str ");
Enter fullscreen mode Exit fullscreen mode

Along with whitespace an argument can be past in to specify a specific string to strip off.

Find a String

find

Rather than reiterate here, see my previous post. I also am preparing the next post which dives into more of the variations.

Regular Expressions

The standard regex library is very nice. I won't be going over examples because regular expressions themselves are a more advanced topic.

https://dlang.org/phobos/std_regex.html

Top comments (0)