| Thread overview |
|---|
April 16, 2017 D version of C# code | ||||
|---|---|---|---|---|
| ||||
What would you put instead of this C# code, in D?
```C#
// Arrange
const string templateString = "My {pet} has {number} {ailment}.";
var pairs = new
{
pet = "dog",
number = 5,
ailment = "fleas",
};
// Act
var result = TemplateStringInterpolator.ReplaceTokens(templateString, pairs);
// Assert
result.Should().Be("My dog has 5 fleas.");
```
I've made a function for strings:
```D
string replaceTokens(in string tmpString, in string[string] aa) {
import std.array : replace;
string result = tmpString;
foreach(key, value; aa) {
string addBits(in string root) {
return "{" ~ root ~ "}";
}
result = result.replace(addBits(key), value);
}
return result;
}
```
| ||||
April 16, 2017 Re: D version of C# code | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Joel | On 04/16/2017 11:20 AM, Joel wrote: > What would you put instead of this C# code, in D? > > ```C# > // Arrange > const string templateString = "My {pet} has {number} > {ailment}."; > var pairs = new > { > pet = "dog", > number = 5, > ailment = "fleas", > }; > > // Act > var result = > TemplateStringInterpolator.ReplaceTokens(templateString, pairs); > > // Assert > result.Should().Be("My dog has 5 fleas."); > ``` void main() { // Arrange const string templateString = "My {pet} has {number} {ailment}."; auto pairs = [ "pet": "dog", "number": "5", "ailment": "fleas", ]; // Act import std.regex: regex, replaceAll; auto result = templateString .replaceAll!(m => pairs[m[1]])(regex(`\{([^}]+)\}`)); // Assert assert(result == "My dog has 5 fleas."); } | |||
April 17, 2017 Re: D version of C# code | ||||
|---|---|---|---|---|
| ||||
Posted in reply to ag0aep6g | On Sunday, 16 April 2017 at 09:46:13 UTC, ag0aep6g wrote:
> On 04/16/2017 11:20 AM, Joel wrote:
>> [...]
>
> void main()
> {
> // Arrange
> const string templateString = "My {pet} has {number} {ailment}.";
> auto pairs = [
> "pet": "dog",
> "number": "5",
> "ailment": "fleas",
> ];
>
> // Act
> import std.regex: regex, replaceAll;
> auto result = templateString
> .replaceAll!(m => pairs[m[1]])(regex(`\{([^}]+)\}`));
>
> // Assert
> assert(result == "My dog has 5 fleas.");
> }
Thanks, ag0aep6g.
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply