6.把123456789轉換為12-345-6789的3種方法
方法一:
C# CODE
string a = "123456789";
a = int.Parse(a).ToString("##-###-####");
Console.Write(a);
方法二:
C# CODEstring a = "123456789";
a = a.Insert(5, "-").Insert(2, "-");
Console.Write(a);
方法三:
C# CODE
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1{
class Program {
static void Main()
{
string a = "123456789";
Regex reg = new Regex(@"^(d{2})(d{3})(d{4})$");
a = reg.Replace(a, "$1-$2-$3");
Console.Write(a);
}
}}
7.交換兩個指定位置字符的4種方法
方法一:
C# CODE
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());
}
方法二:
C# CODE
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);
}