-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringExtension.cs
89 lines (67 loc) · 2.65 KB
/
StringExtension.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
namespace TwoBySixAntennaSwitch
{
public static class StringExtension
{
public static string PadLeft(this string text, int totalWidth)
{
return PadLeft(text, totalWidth, ' ');
}
public static string PadLeft(this string text, int totalWidth, char paddingChar)
{
if (totalWidth < 0)
throw new ArgumentOutOfRangeException("totalWidth", "< 0");
if (totalWidth < text.Length)
return text;
if (totalWidth == 0)
return string.Empty;
while (totalWidth > text.Length)
{
text = paddingChar + text;
}
return text;
}
public static string PadRight(this string text, int totalWidth)
{
return PadRight(text, totalWidth, ' ');
}
public static string PadRight(this string text, int totalWidth, char paddingChar)
{
if (totalWidth < 0)
throw new ArgumentOutOfRangeException("totalWidth", "< 0");
if (totalWidth < text.Length)
return text;
if (totalWidth == 0)
return string.Empty;
while (totalWidth > text.Length)
{
text = text + paddingChar;
}
return text;
}
/// <summary>
/// Replace all occurances of the 'find' string with the 'replace' string.
/// </summary>
/// <param name="content">Original string to operate on</param>
/// <param name="find">String to find within the original string</param>
/// <param name="replace">String to be used in place of the find string</param>
/// <returns>Final string after all instances have been replaced.</returns>
public static string Replace(this string content, string find, string replace)
{
const int startFrom = 0;
int findItemLength = find.Length;
int firstFound = content.IndexOf(find, startFrom);
var returning = new StringBuilder();
string workingString = content;
while ((firstFound = workingString.IndexOf(find, startFrom)) >= 0)
{
returning.Append(workingString.Substring(0, firstFound));
returning.Append(replace);
// the remaining part of the string.
workingString = workingString.Substring(firstFound + findItemLength, workingString.Length - (firstFound + findItemLength));
}
returning.Append(workingString);
return returning.ToString();
}
}
}