Search code examples
c#.netstringconcatenationcapitalize

How can I concatenate a text capitalized by a foreach loop in C#?


using System;

class Program{
  public static void Main (string[] args){
    string Text = "the sentence which each word must be capitalized";
    string[] WordArray = new string[8];

    foreach (string Word in Text.Split(' ')){
      string CapitalizedFirstLetter = Word.Substring(0, 1).ToUpper();
      string RestOfWord = Word.Substring(1, Word.Length-1);
      string ConcatenatedWord = string.Concat(CapitalizedFirstLetter, RestOfWord);
    }
  }
}

I was planning to capitalize each words and concatenate it again but, I cannot concatenate it. How should I concatenate it?


Solution

  • you can try this

    string text = "the sentence which each word must be capitalized";
    
    var words = text.Split(" ");
    
    for (var i = 0; i < words.Length; i++) words[i] =  
    Char.ToUpper(words[i][0]).ToString()+words[i].Substring(1);
    
    text = string.Join(" ", words);