交换两个指定位置字符的4种方法

 

方法一:


static void Main()
        ...{
            string s = "123456789";
            SwapChar(ref s, 3, 6);
            Console.Write(s.ToString());
        }

        static void SwapChar(ref string s, int i1, int i2)
        ...{
            char temp = s[i1];
            char temp1 = s[i2];
            s = s.Remove(i1, 1).Insert(i1, temp1.ToString());
            s = s.Remove(i2, 1).Insert(i2, temp.ToString());
        }

方法二:


 static void Main()
        ...{
            string s = "123456789";
            //SwapChar(s, 3, 6);
            Console.Write(SwapChar(s, 3, 6).ToString());
        }

        static string SwapChar(string s, int p1, int p2)
        ...{
            if ((p1 == p2) || ((p1 < 0) || (p2 < 0))) return s;
            if ((p1 >= s.Length) || (p2 >= s.Length)) return s;
            char[] vChars = s.ToCharArray();
            vChars[p1] = (char)(vChars[p2] | (vChars[p2] = vChars[p1]) & 0);
            return new string(vChars);
        }

方法三:


static void Main()
        ...{
            string s = "123456789";
            Console.Write(SwapChar(s, 3, 6).ToString());
        }

        public static string SwapChar(string str, int a, int b)
        ...{
            char[] newStr = str.ToCharArray();
            newStr[a] = str[b];
            newStr[b] = str[a];
            return new string(newStr);
        }
 

方法四:


using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
...{
    class Program
    ...{
        static void Main()
        ...{
            string s = "123456789";
            Console.Write(SwapChar(s, 3, 6).ToString());
        }

        static string SwapChar(string s, int p1, int p2)
        ...{
            if (p1 > p2) ...{ int p = p1; p1 = p2; p2 = p; }
            return Regex.Replace(s, "^(.{" + p1 + "})(.)(.{" + (p2 - p1 - 1) + "})(.)(.*)$", "$1$4$3$2$5");
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值