首页WEB开发.NET教程 → C#优化字符串操作

C#优化字符串操作

日期:2007-10-5 11:10:22 出处:清清月儿 作者:清清月儿 人气:
上一页 [1] [2] [3] [4] 下一页

7.交换两个指定位置字符的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");
}


}

}

 

8. “%10”的妙用

static void Main()
        {

            Random r = new Random();

            Console.WriteLine(r.Next() % 10);//1-9
            Console.WriteLine(r.Next() % 10);
            Console.WriteLine(r.Next() % 10);
            Console.WriteLine(r.Next() % 10);
            Console.WriteLine(r.Next() % 10);
            Console.WriteLine(r.Next() % 10);
            Console.WriteLine(r.Next() % 10);
            Console.WriteLine(r.Next() % 10);
            Console.WriteLine(r.Next() % 10);
        }

 

9.输出21个AAAAAAAAAAAAAAAAAAAAA的巧妙做法

new构造器的理解
如果要你创建一个由21个"A"字符构成的字符串,你会怎么做?
string str = "AAAAAAAAAAAAAAAAAAAAA";//老实型
string str = new string('A', 21);//简单聪明

10.compare()与compareTo()方法

一样的功能,只是两个接口的两个方法而已  
  compare是Comparatable的方法,compareTo是Comparator的方法

上一页 [1] [2] [3] [4] 下一页

关于本站 | 帮 助 | 广告服务 | 版权声明 | 业务合作 | 捐助本站 | 软件发布 | 联系我们
77资源下载 www.77zy.com ©2007-2008 版权所有
备案编号:赣ICP备07002641号  QQ:674648476