Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capitalize and lower case the rest c#

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading