-3
using System;
using System.Collections.Generic;
public class Program
{
     public static void Main()
 {
  List<string> stringList = new List<string>{"abca","two","three","four","five","six"};
  stringList.ForEach(x=>{
   Console.WriteLine(x.Replace(x[0],Char.ToUpper(x[0])));
  });
 }
}

program to replace the first letter with capital letter in each sentences using c# console application but its providing the output like "AbcA".

Jagath Karra
  • 87
  • 1
  • 2
  • 8

2 Answers2

3

You program will not work for if the list contains "abca", the output will be "AbcA".

use instead this:

char.ToUpper(x[0]) + x.Substring(1);

I let you manage the case when x is empty or has only one character

Hassan
  • 313
  • 1
  • 2
  • 12
  • I am replacing the first character of the string x.Replace(x[0],Char.ToUpper(x[0])) . so it will work for the string contains "abca" then the output will be "Abca" – Jagath Karra Oct 18 '18 at 07:36
  • 1
    @Jagath No, you are instructing [`Replace()`](https://learn.microsoft.com/dotnet/api/system.string.replace#System_String_Replace_System_Char_System_Char_) to replace _all occurrences_ of the `char` at `x[0]` (`'a'`) with `Char.ToUpper(x[0])` (`'A'`). Just because the `char` you specify to be replaced happens to be the first `char` of the `string` does not limit `Replace()`'s search to the first `char` of the `string`. If you [run your snippet](https://dotnetfiddle.net/Widget/aouIXJ) you will see the result is `"AbcA"` not `"Abca"`. – Lance U. Matthews Oct 18 '18 at 19:31
  • @BACON thanks for your idea. I tried it gives like "AbcA" so I have changed like char.ToUpper(x[0]) + x.Substring(1) this and its working fine now. – Jagath Karra Oct 22 '18 at 06:45
-3
using System;
using System.Collections.Generic;
public class Program
{
 public static void Main()
 {
  List<string> stringList = new List<string>{"one","two","three","four","five","six"};
  stringList.ForEach(x=>{
   Console.WriteLine(char.ToUpper(x[0]) + x.Substring(1););
  });
 }
}   

program to replace the first letter with capital letter in each sentences using c# console application.

Output :
One
Two
Three
Four
Five
Six
Jagath Karra
  • 87
  • 1
  • 2
  • 8
  • Try with sample string `"abca"`, as the OP did - it will fail for the same reason – Hans Kesting Oct 22 '18 at 08:01
  • @HansKesting I have tried it gives the wrong out put. then I have used above answer from "Hassen" char.ToUpper(x[0]) + x.Substring(1); its working fine for me. – Jagath Karra Oct 22 '18 at 13:20
  • Ah, you *are* the OP. While you *are* allowed to *answer* your own question, this should have been an edit to your original question. You can still do that and delete this "answer" – Hans Kesting Oct 22 '18 at 13:26