|
1 | 1 | using System;
|
| 2 | +using System.Text; |
2 | 3 |
|
3 | 4 | namespace JsonApiDotNetCore.Extensions
|
4 | 5 | {
|
5 | 6 | public static class StringExtensions
|
6 | 7 | {
|
7 | 8 | public static string ToCamelCase(this string str)
|
8 | 9 | {
|
9 |
| - var splittedPhraseChars = str.ToCharArray(); |
10 |
| - if (splittedPhraseChars.Length > 0) |
| 10 | + var chars = str.ToCharArray(); |
| 11 | + if (chars.Length > 0) |
11 | 12 | {
|
12 |
| - splittedPhraseChars[0] = new string(splittedPhraseChars[0], 1).ToLower().ToCharArray()[0]; |
13 |
| - return new String(splittedPhraseChars); |
| 13 | + chars[0] = new string(chars[0], 1).ToLower().ToCharArray()[0]; |
| 14 | + return new String(chars); |
14 | 15 | }
|
15 | 16 | return str;
|
16 | 17 | }
|
| 18 | + |
17 | 19 | public static string ToProperCase(this string str)
|
18 | 20 | {
|
19 |
| - var splittedPhraseChars = str.ToCharArray(); |
20 |
| - if (splittedPhraseChars.Length > 0) |
| 21 | + var chars = str.ToCharArray(); |
| 22 | + if (chars.Length > 0) |
| 23 | + { |
| 24 | + chars[0] = new string(chars[0], 1).ToUpper().ToCharArray()[0]; |
| 25 | + return new String(chars); |
| 26 | + } |
| 27 | + return str; |
| 28 | + } |
| 29 | + |
| 30 | + public static string Dasherize(this string str) |
| 31 | + { |
| 32 | + var chars = str.ToCharArray(); |
| 33 | + if (chars.Length > 0) |
21 | 34 | {
|
22 |
| - splittedPhraseChars[0] = new string(splittedPhraseChars[0], 1).ToUpper().ToCharArray()[0]; |
23 |
| - return new String(splittedPhraseChars); |
| 35 | + var builder = new StringBuilder(); |
| 36 | + for(var i = 0; i < chars.Length; i++) |
| 37 | + { |
| 38 | + if(char.IsUpper(chars[i])) { |
| 39 | + var hashedString = (i > 0) ? $"-{char.ToLower(chars[i])}" : $"{char.ToLower(chars[i])}"; |
| 40 | + builder.Append(hashedString); |
| 41 | + } |
| 42 | + else { |
| 43 | + builder.Append(chars[i]); |
| 44 | + } |
| 45 | + } |
| 46 | + return builder.ToString(); |
24 | 47 | }
|
25 | 48 | return str;
|
26 | 49 | }
|
|
0 commit comments