Home > Back-end >  Is there a way to properly case names after user inputs their names in C#?
Is there a way to properly case names after user inputs their names in C#?

Time:04-01

I am trying to figure out how to sort input names to right capitalization eg: tim jAmes = Tim James

I have sorted it up to where i can take in the name, but the sorting out has been doing my head in, not very familiar with c# yet but i need this for a test i am doing .

Here's my exisiting code:

Console.WriteLine("What is your name?");
var str = Console.ReadLine();

Console.WriteLine("Hello there, "   str);

CodePudding user response:

This is a simple approach:

Console.WriteLine("What is your name?");
var str = Console.ReadLine();

TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
str = textInfo.ToTitleCase(str); 
Console.WriteLine("Hello there, "   str); //Hello there, Tim James

Just make sure that you include: using System.Globalization; at the top

CodePudding user response:

You can roll your own by using static methods of the char class.

The idea is to only capitalize characters that are preceded by whitespace. This is a naive way of approaching this, but fun to tinker around with.

var input = "TIM JAMES";
var output = "";
var thisChar = ' ';
var shouldCapitalize = true;

for (int i = 0; i < input.Length; i  )
{
    thisChar = input[i];

    if (char.IsWhiteSpace(thisChar))
    {
        shouldCapitalize = true;
    }
    else
    {
        if (shouldCapitalize)
        {
            thisChar = char.ToUpper(thisChar);
            shouldCapitalize = false;
        }
        else
        {
            thisChar = char.ToLower(thisChar);
        }
    }

    output  = thisChar;
}

Console.WriteLine("Hello there, "   output);

CodePudding user response:

This cannot be done reliably because there are just many different kind of names that don't follow the basic rule with the first letter being capital followed by lowercase letters. One example is Neil deGrasse Tyson.

You may try ToTitleCase as others suggested - and this even covers , but if you doing this as an exercise to learn programming you could go back to basics and try with Split and ToLower and ToUpper:

using System.Globalization;

var name = "tim jAmes";

Console.WriteLine($"{name} => {FixName(name)}");

string FixName(string name)
{
    var culture =  new CultureInfo(name: "en-US", useUserOverride: false);

    if( name.ToLower() == "Neil deGrasse Tyson".ToLower())
    {
        return "Neil deGrasse Tyson"; // ;)
    }

    var parts = name.Split(" ");
    var fixedParts = new List<string>();
    foreach(var part in parts)
    {
        var fixedPart = char.ToUpper(part[0], culture) 
                        part.Substring(startIndex: 1).ToLower(culture);
        fixedParts.Add(fixedPart);
    }

    var fixedName = string.Join(" ", fixedParts);
    return fixedName;
}

This prints:

tim jAmes => Tim James
  • Related