How to swap a characters in a string by index with C#

1 Answer

0 votes
using System;

class Program
{
    public static String swap(String s, int i, int j) {
        char[] charArray = s.ToCharArray();
         
        char temp = charArray[i] ;
        charArray[i] = charArray[j];
        charArray[j] = temp;
         
        return new string(charArray);
    }

    static void Main() {
        string s = "abcd";
           
        s = swap(s, 0, 2);
        
        Console.Write(s);
    }
}





/*
run:

cbad

*/

 



answered Sep 5, 2021 by avibootz
edited Sep 5, 2021 by avibootz

Related questions

2 answers 171 views
2 answers 172 views
3 answers 233 views
1 answer 162 views
1 answer 143 views
1 answer 264 views
1 answer 187 views
...