0

I'm struggling with formatting a string. When my value is like: OrderLineId and want to format this to: order_line_id. All lowercase and each uppercase char should be appended with a _ except the first character.

I do see some use of TextInfo of the using System.Globalization; but I can't get my head to fix this.

I try to fix this with just C# code, rather not Regex.... sorry

Thanks in advance.

ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
Leroy Meijer
  • 1,169
  • 17
  • 40
  • Does `new String(text.SelectMany(x => char.IsUpper(x) ? "_" + x.ToString().ToLower() : x.ToString()).ToArray()).TrimStart('_')` work for you? – Enigmativity Aug 12 '18 at 09:40
  • Try following : string input = "OrderLineId"; string output = input.Substring(0, 1).ToLower() + string.Join("", input.Skip(1).Select(x => char.IsUpper(x) ? "_" + char.ToLower(x).ToString() : x.ToString())); – jdweng Aug 12 '18 at 09:48

1 Answers1

1

based on this question:

Add spaces before Capital Letters

I have tweaked the answer for your purpose.

string AddUnderScoresToSentence(string text)
    {
        if (string.IsNullOrWhiteSpace(text))
            return "";
        StringBuilder newText = new StringBuilder(text.Length * 2);
        newText.Append(text[0]);
        for (int i = 1; i < text.Length; i++)
        {
            if (char.IsUpper(text[i]) && text[i - 1] != '_')
                newText.Append('_');
            newText.Append(text[i]);
        }
        string result = newText.ToString();
        return result.ToLower();
    }
Rutger Vk
  • 190
  • 5