-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathStringFunctions.cs
85 lines (78 loc) · 2.56 KB
/
StringFunctions.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
using System.Collections.Generic;
using System.Linq;
namespace NTypewriter.CodeModel.Functions
{
/// <summary>
/// Set of functions that operates on String
/// </summary>
public static class StringFunctions
{
/// <summary>
/// Converts text case to CamelCase
/// </summary>
public static string ToCamelCase(this string text)
{
var words = text.SplitIntoSeparateWords();
return string.Join("", words.Select(x => x.ToLower().ToUpperFirst())).ToLowerFirst();
}
/// <summary>
/// Converts first letter of the given string to upper case
/// </summary>
public static string ToUpperFirst(this string text)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
char[] a = text.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
/// <summary>
/// Converts first letter of the given string to lower case
/// </summary>
public static string ToLowerFirst(this string text)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
char[] a = text.ToCharArray();
a[0] = char.ToLower(a[0]);
return new string(a);
}
/// <summary>
/// It tries to extract separate words from string
/// </summary>
public static IEnumerable<string> SplitIntoSeparateWords(this string text)
{
int wordFirstIndex = 0;
for (int i = 0; i < text.Length; ++i)
{
if (!char.IsLetterOrDigit(text[i]))
{
int wordLength = i - wordFirstIndex;
if (wordLength > 0)
{
yield return text.Substring(wordFirstIndex, wordLength);
}
wordFirstIndex = i + 1;
}
if (char.IsUpper(text[i]))
{
int wordLength = i - wordFirstIndex;
if (wordLength > 0)
{
yield return text.Substring(wordFirstIndex, wordLength);
}
wordFirstIndex = i;
}
}
int remainderLength = text.Length - wordFirstIndex;
if (remainderLength > 0)
{
yield return text.Substring(wordFirstIndex, remainderLength);
}
}
}
}