How to replace a char at a given index in string in C#

3 Answers

0 votes
using System;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "you are a great programmer, keep practice";
            StringBuilder sb = new StringBuilder(s);

            try
            {
                sb[0] = 'Y';
                s = sb.ToString();
                Console.WriteLine(s);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

}

/*
run:
   
You are a great programmer, keep practice
 
*/


answered May 29, 2015 by avibootz
0 votes
using System;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "you are a great programmer, keep practice";

            try
            {
                s = ReplaceChar(s, 0, 'Y');
                Console.WriteLine(s);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public static string ReplaceChar(string s, int i, char ch)
        {
            if (s == null)
            {
                throw new ArgumentNullException("s");
            }
            StringBuilder sb = new StringBuilder(s);
            sb[i] = ch;

            return sb.ToString();
        }
    }

}

/*
run:
   
You are a great programmer, keep practice
 
*/


answered May 29, 2015 by avibootz
0 votes
using System;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "you are a great programmer, keep practice";

            try
            {
                s = ReplaceChar(s, 0, 'Y');
                Console.WriteLine(s);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public static string ReplaceChar(string s, int i, char ch)
        {
            if (s == null)
            {
                throw new ArgumentNullException("s");
            }
            char[] ch_arr = s.ToCharArray();
            ch_arr[i] = ch;

            return new string(ch_arr);
        }
    }

}

/*
run:
   
You are a great programmer, keep practice
 
*/


answered May 29, 2015 by avibootz

Related questions

1 answer 148 views
1 answer 183 views
1 answer 208 views
1 answer 136 views
1 answer 150 views
1 answer 175 views
...