交换两个指定位置字符的4种方法
2012-01-17 11:32
393 查看
方法一:
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");
}
}
}
相关文章推荐
- 交换两个指定位置字符的4种方法
- 两个操作字符串的方法:读取指定位置的字符和找出某个字符串的位置
- c语言:4种方法;交换两个整数的位置(包括引入第三方变量和不引入第三方变量)
- c语言:4种方法;交换两个整数的位置(包括引入第三方变量和不引入第三方变量)
- JavaScript字符串对象charAt方法入门实例(用于取得指定位置的字符)
- JS之返回指定位置字符的charAt方法
- JavaScript indexOf方法入门实例(计算指定字符在字符串中首次出现的位置)
- 用C语言实现给定两个整形变量的值,将两个值的内容进行交换。(4种方法)
- 链表的基本操作(创建,查找指定位置元素,删除指定元素,插入,倒置,去重,求集合的差,分别交换结点与交换结点值实现的冒泡排序,将两个有序链表合并成一个有序链表)c语言实现
- pyghon list指定位置插入字符的方法
- js中两个常用方法(1.获取当前工程的虚拟目录;2.移除数组指定位置上的元素)
- JavaScript lastIndexOf方法入门实例(计算指定字符在字符串中最后一次出现的位置)
- 【python】去掉字符串中某个指定位置的字符的几种方法
- JavaScript indexOf方法入门实例(计算指定字符在字符串中首次出现的位置)
- JavaScript lastIndexOf方法入门实例(计算指定字符在字符串中最后一次出现的位置)
- charAt()方法获取指定位置的字符
- python 替换字符串中指定位置字符——一个简单有效的方法
- JavaScript charCodeAt方法入门实例(用于取得指定位置字符的Unicode编码)
- JavaScript字符串对象charAt方法入门实例(用于取得指定位置的字符)
- jQuery实现在textarea指定位置插入字符或表情的方法