Click here to Skip to main content
15,887,746 members
Articles / Programming Languages / C#
Tip/Trick

CaseConverter: A Class for Converting to Different Casing Styles

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
6 Feb 2024MIT 2.1K   16   2  
Easily convert identifiers from one casing style to another with this simple to use class
Code generators often need to do case conversion in order to convert friendly names or names from other structured text documents to appropriately cased identifiers in your code. Here's some code for doing exactly that.

Introduction

I wrote this code twice. The first time, I lost it somewhere in the depths of Azure. I write a lot of code generators so being able to convert for example, camelCase to snake_case, or IPAddress to IP_ADDRESS is especially useful.

Using the Code

You can do two things with this code. The first thing is you can split a string into multiple segments ("words") each containing part of your identifier. For example, "IPAddress" would net you "IP" and "Address" and "WiFi" would net you "Wi" and "Fi". You do this using the SplitCase() function which takes a string and returns an array of strings.

The other thing you can do is convert to a different case with Convert(). Convert takes a string and a CaseStyle and returns a string.

C#
using CaseConvert;
var exps = new string[]
{
    "foobar",
    "foo_baz",
    "IPAddress",
    "SQL92",
    "WiFi",
    "ISO8601",
    "fuBar",
    "C89"
};

for(int i = 0; i < exps.Length; i++)
{
    var sa = CaseConverter.SplitCase(exps[i]);
    Console.WriteLine("segments: "+string.Join(", ",sa)); 
    Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.PascalCase));
    Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.CamelCase));
    Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.SnakeCase));
    Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.DashCase));
    Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.MacroCase));
    Console.WriteLine();
}

History

  • 6th February, 2024 - Initial submission

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
United States United States
Just a shiny lil monster. Casts spells in C++. Mostly harmless.

Comments and Discussions

 
-- There are no messages in this forum --