How to replace char in a string by index with C#

1 Answer

0 votes
using System;
using System.Text;
 
class Program
{
    static string replace_char(string s, int idx, char ch) { 
        int len = s.Length; 
        
        if (idx < 0 || idx > len) return s;
  
        StringBuilder sb = new StringBuilder(s);
         
        sb[idx] = ch;
         
        return sb.ToString();
    } 
    static void Main() {
        string s = "c# programming"; 
  
        s = replace_char(s, 3, 'G');
 
        Console.Write(s);
    }
}
 
 
 
/*
run:
 
c# Grogramming
 
*/

 



answered Nov 16, 2019 by avibootz
edited Nov 18, 2019 by avibootz

Related questions

3 answers 362 views
1 answer 167 views
1 answer 146 views
1 answer 144 views
1 answer 153 views
1 answer 191 views
...