-2

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 lowercase the others in order to get the result:

First name
Birth of date

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

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Jesus
  • 331
  • 1
  • 4
  • 19
  • you want to capitalize from the splitted string or from the original string? – Vivek Nuna Jan 10 '23 at 03:24
  • 1
    Reading the answers to other questions will be helpful. For example, the question about [Splitting camel case](https://stackoverflow.com/questions/773303/splitting-camelcase) is likely helpful. Also relevant is how to [Make first letter of a string upper case](https://stackoverflow.com/questions/4135317/make-first-letter-of-a-string-upper-case-with-maximum-performance) – Wyck Jan 10 '23 at 03:26
  • From the splitted string @letsdoit – Jesus Jan 10 '23 at 03:28
  • Is a string list or a string with vreak line? – MichaelMao Jan 10 '23 at 06:56

3 Answers3

1

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"
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
1

I would use StringBuilder in Aggregate() method like this:

string input = "earthIndiaUSA";
var output = input.Select((c, idx) => (c, idx))
                  .Aggregate(new StringBuilder(), (sb, t) => 
                             t.idx == 0 
                                 ? sb.Append(Char.ToUpper(t.c)) 
                                 : Char.IsUpper(t.c) 
                                     ? sb.Append(' ').Append(t.c) 
                                     : sb.Append(t.c))
                  .ToString();

output will be "Earth India U S A"

ASh
  • 34,632
  • 9
  • 60
  • 82
1

I agree with the already mentioned StringBuilder (from the System.Text namespace) approach, but I would suggest creating a helper method to do the string creations. Such a method is easy to reuse (e.g. when converting several strings collected in a list/array), and can display clearly how each character in the source string is handled. Maintenance / Making changes to the conversion logic at a later time will also be quite easy.

Suggested implementation:

private static string GetSentence(string str)
{
    var sb = new StringBuilder();
    
    sb.Append(Char.ToUpper(str[0])); // Handle the first char
    
    foreach (var ch in str[1..]) // Then, handle the remaining chars
    {
        if (Char.IsUpper(ch))
        {
            sb.Append(' ');
            sb.Append(Char.ToLower(ch));
        }
        else
        {
            sb.Append(ch);  
        }
    }
    
    return sb.ToString();
}

It can be used on an array of strings, like this:

var strings = new[] { "firstName", "birthOfDate" };

var sentences = strings
    .Select(GetSentence)
    .ToArray();

foreach (var sentence in sentences)
{
    Console.WriteLine(sentence);
}

which produces:

First name
Birth of date

In the example above, the .Select() method is found in the System.Linq namespace.


Example fiddle here.

Astrid E.
  • 2,280
  • 2
  • 6
  • 17