/
StringRenderer.cs
54 lines (42 loc) · 1.1 KB
/
StringRenderer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
using System.Linq;
namespace KataStringReplacer
{
public class StringRenderer
{
private Dictionary<string, string> _placeholders;
public StringRenderer(Dictionary<string, string> placeholders)
{
_placeholders = placeholders;
}
public string Render(string template)
{
if (_placeholders != null)
foreach (var keyValue in _placeholders)
template = template.Replace(GetPlaceholder(keyValue.Key), keyValue.Value);
template = RemoveUnrecognizedPlaceholders(template);
return template;
}
private string GetPlaceholder(string name)
{
return String.Format("${0}$", name);
}
private string RemoveUnrecognizedPlaceholders(string text)
{
int tokenStart, tokenEnd = -1;
do
{
tokenStart = text.IndexOf('$');
if (tokenStart > -1)
{
tokenEnd = text.IndexOf('$', tokenStart + 1);
if (tokenEnd > tokenStart)
text = text.Substring(0, tokenStart) + text.Substring(tokenEnd + 1);
}
}
while (tokenEnd > tokenStart && tokenStart > 0);
return text;
}
}
}