C# program to replace n-th character from a given index in a string


Firstly, set a string.

string str1 = "Port";
Console.WriteLine("Original String: "+str1);

Now convert the string into character array.

char[] ch = str1.ToCharArray();

Set the character you want to replace with the index of the location. To set a character at position 3rd.

ch[2] = 'F';

To remove nth character from a string, try the following C# code. Here, we are replacing the first character.

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(string[] args) {
      string str1 = "Port";
      Console.WriteLine("Original String: "+str1);
      char[] ch = str1.ToCharArray();
      ch[0] = 'F';
      string str2 = new string (ch);
      Console.WriteLine("New String: "+str2);
   }
}

Output

Original String: Port
New String: Fort

Updated on: 23-Jun-2020

851 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements