Mohanapriya R Mohanapriya R
Updated date Apr 27, 2024
In this article, we will learn how to convert your strings into snake case using C#.
  • 2.6k
  • 0
  • 0

What is Snake Case?

Snake case is a naming convention where words in a compound phrase are joined by underscores, and the entire phrase is in lowercase. For example, "helloWorld" becomes "hello_world" in snake case.

Convert Strings to Snake Case in C#

Below is a simple C# program that converts a given string to snake case using a method named ConvertToSnakeCase:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string inputString = "ConvertThisStringTo_SnakeCase";

        string snakeCaseString = ConvertToSnakeCase(inputString);

        Console.WriteLine($"Original String: {inputString}");
        Console.WriteLine($"Snake Case String: {snakeCaseString}");
    }

    static string ConvertToSnakeCase(string input)
    {
        // Use regex to insert underscores before capital letters
        string snakeCase = Regex.Replace(input, "([a-z])([A-Z])", "$1_$2").ToLower();
        return snakeCase;
    }
}
  • We start by defining a sample input string with a mix of uppercase and lowercase characters and underscores.
  • The ConvertToSnakeCase method uses a regular expression to insert underscores before capital letters.
  • The ToLower method is then called to ensure that the entire string is in lowercase.

Output:

When you run the program, you should see the following output:

Original String: ConvertThisStringTo_SnakeCase
Snake Case String: convert_this_string_to_snake_case

Comments (0)

There are no comments. Be the first to comment!!!