Home > Enterprise >  Capitalize and lower case the rest c#
Capitalize and lower case the rest c#

Time:01-10

I have simple strings as:

firstName
birthOfDate

I want to format them by adding space on each capital letter, so I try with LINQ as:

var actitivityDescription = string.Concat(activity.Description.Select(x => Char.IsUpper(x) ? " "   x : x.ToString())).TrimStart(' ');

And it works; it shows values as:

first Name
birth Of Date

Now, I want to capitalize the first letter and lower case the others in order to get the result as:

First name
Birth of date

How can I achieve that, is it possible to do it in the same LINQ expression?

CodePudding user response:

you can do like this.

split the string by space then change the first word's first letter to upper case and the rest of the string's first word's first letter to lower case.

string input = "birth Of Date";

string[] words = input.Split(' ');

words[0] = words[0].First().ToString().ToUpper()   words[0].Substring(1);

for (int i = 1; i < words.Length; i  )
{
    words[i] = words[i].First().ToString().ToLower()   words[i].Substring(1);
}

string output = string.Join(" ", words);

Console.WriteLine(output);  // Output: "Birth of date"

Here is the version using Select with the same logic.

string input = "birth Of Date";

string[] words = input.Split(' ');

string[] modifiedWords = words.Select((word, index) =>
    index == 0 ? word.First().ToString().ToUpper()   word.Substring(1) : word.First().ToString().ToLower()   word.Substring(1)).ToArray();

string output = string.Join(" ", modifiedWords);

Console.WriteLine(output);  // Output: "Birth of date"
  • Related