2016-12-12 11:46:15 u011127019 阅读数 2962

一、C#字符串连接和StringBuilder字符串拼接性能测试

Environment.TickCount,距离系统启动时间为基准,对比代码执行时间。

/// <summary>
/// 实例测试,C#字符串链接和StringBuilder的性能
/// </summary>
static void StringTest()
{
    // 获取系统启动后经过的毫秒数。
    int start = Environment.TickCount;
    /******使用字符串连接构建字符串******/
    for (int i = 0; i < 200; i++)
    {
        string s = "";
        for (int j = 0; j < 1000; j++)
        {
            s += "Outer index=";
            s += i;
            s += "Inner index=";
            s += j;
            s += " ";
        }
    }
    int middle = Environment.TickCount;
    Console.WriteLine("字符串拼接时间:{0}秒", (middle - start) / 1000);
    /******使用StringBuilder构建字符串******/
    for (int i = 0; i < 20; i++)
    {
        StringBuilder builder = new StringBuilder();
        for (int j = 0; j < 1000; j++)
        {
            builder.Append("Outer index=");
            builder.Append(i);
            builder.Append("Inner index=");
            builder.Append(j);
            builder.Append(" ");
        }
    }
    int end = Environment.TickCount;
    Console.WriteLine("StringBuilder拼接时间:{0}毫秒,约等于{1}秒", (end - middle), (end - middle) / 1000);
}

结果对比



特别说明:

对于有大量字符串拼接操作或者说在大量循环操作中,需要拼接字符串的时候,就必须考虑性能问题。

解决方案之一就是使用StringBuilder类。

    //
    // 摘要:
    //     表示可变字符字符串。此类不能被继承。
    [ComVisible(true)]
    [DefaultMember("Chars")]
    public sealed class StringBuilder : ISerializable


2014-06-23 10:40:36 KingCruel 阅读数 1036
C#字符串处理、字符串转数组、数组转字符串


一、指示指定的String对象是空引用还是Empty字符串。(如果value参数为空引用或空字符串 (""),则为true;否则为 false。)
  if (!string.IsNullOrEmpty("字符串"))
  {}


二、定义字符串
  string str= string.Empty;


三、IDataReader中读取数据空字符串处理
  if (reader["MessageHistoryID"] == DBNull.Value)
  {
      model.IsRead = true;
  }


  if(ds.Tables[0].Rows[0]["ID"].ToString()!="")
  {
      model.ID=int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());
  }


四、List<int>集合转换为字符串
  List<int> list = new List<int>();
  list.Add(100);
  list.Add(90);
  list.Add(60);
  list.Add(80);
  list.Add(10);
  list.Add(40);
  list.Add(20);
  list.Add(10);
  list.Add(50);
  list.Add(50);


  ///所见即所得
  string strArr = string.Join(",", list.ToArray());
  ///升序
  string strArrOrderBy = string.Join(",", list.ToArray().OrderBy(o => o));
  ///降序
  string strArrOrderByDesc = string.Join(",", list.ToArray().OrderByDescending(o => o));
  ///去除重复
  string strArrDistinct = string.Join(",", list.ToArray().Distinct());
  ///排序、去除重复
  string strArrOrderByDescDistinct = string.Join(",", list.ToArray().OrderByDescending(o => o).Distinct());


  strArr输出结果:100,90,60,80,10,40,20,10,50,50
  strArrOrderBy输出结果:10,10,20,40,50,50,60,80,90,100
  strArrOrderByDesc输出结果:100,90,80,60,50,50,40,20,10,10
  strArrDistinct输出结果:100,90,60,80,10,40,20,50
  strArrOrderByDescDistinct输出结果:100,90,80,60,50,40,20,10


五、字符串转数组
  #region 字符串转数组
  List<int> listArr = new List<int>();
  string str = "gfedfdasfdasferwq431241324321ablk";
  var query = from s in str orderby s select s;
  char[] sortStr = query.ToArray();
  string strRes = new string(sortStr);
  Label1.Text = strRes;
  #endregion


  #region 字符串转数组
  List<int> listStrArr = new List<int>();
  string strapp = "19,92,63,45,51,62,47,85,9,10";
  string[] strtemp = strapp.Split(',');
  foreach (string item in strtemp)
  {
      listStrArr.Add(Convert.ToInt32(item));
  }
  Label1.Text = string.Join(",", listStrArr.ToArray());
  
  var num = "1,2,3,4,5,6".Split(',').Select(v => Convert.ToInt32(v)).ToArray();
  string aa = num[0].ToString();
  string bb = num[1].ToString();


  #endregion


六、List<T>.Contains方法(确定某元素是否在 List<T> 中)
  List<int> idList = new List<int>();
  while (reader.Read())
  {
      Message model = Message(reader);
      if (!idList.Contains(model.MessageID))
          idList.Add(model.MessageID);
      list.Add(model);
  }


七、过滤特殊字符
   public string DelQuota(string str)
   {
       string result = str;
       string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
       for (int i = 0; i < strQuota.Length; i++)
       {
           if (result.IndexOf(strQuota[i]) > -1)
               result = result.Replace(strQuota[i], "");
       }
       return result;
   }
2019-05-07 17:29:43 dd_zhouqian 阅读数 87

1.C#字符串多行方式赋值,来自链接 https://bbs.csdn.net/wap/topics/350257775

        private const string f_string1 = @"using System.Windows.Forms;
                                        public class Test
                                        {
                                            public void Hello()
                                            {
                                                MessageBox.Show(""Hello world!"");
                                            }
                                        }";
        private const string f_string2 = @"aaaaaaaaaaaaaaaaaaa
                                           aaaaaaaaaa
                                           aaaaaa";

        private const string f_string3 = "using System.Windows.Forms;" +
                                         "public class Test" +
                                         "{" +
                                             "public void Hello()" +
                                             "{" +
                                                 "MessageBox.Show(\"Hello world!\");" +
                                             "}" +
                                         "}";

2.单行字符串中有双引号

private const string f_string1 = "using System.Windows.Forms (\"hello\")";

3.使用通配符@时,字符串中有双引号,来自链接 https://bbs.csdn.net/topics/390584803

        private const string f_string1 = @"using System.Windows.Forms;
                                        public class Test
                                        {
                                            public void Hello()
                                            {
                                                MessageBox.Show(""Hello world!"");
                                            }
                                        }";

 

 

 

2014-08-17 10:48:36 y_f123 阅读数 2409

    using System;
    using System.Web;
    using System.Text;
    using System.Web.UI.WebControls;
    using System.Text.RegularExpressions;

    public class ValidateHelper
    {
        private static Regex RegNumber = new Regex("^[0-9]+$");
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
        private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
        private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$");
        private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");
        private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
        private static Regex RegTell = new Regex("^(([0-9]{3,4}-)|[0-9]{3.4}-)?[0-9]{7,8}$");
        private static Regex RegSend = new Regex("[0-9]{1}([0-9]+){5}");
        private static Regex RegUrl = new Regex("^[a-zA-z]+://(
\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?|[a-zA-z]+://((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))$");
        private static Regex RegMobilePhone = new Regex("^13|15|18[0-9]{9}$");
        private static Regex RegMoney = new Regex("^[0-9]+|[0-9]+[.]?[0-9]+$");

        #region 数字字符串检查

        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        public static bool IsNumber(string inputData)
        {
            if (!string.IsNullOrEmpty(inputData))
            {
                Match m = RegNumber.Match(inputData);
                return m.Success;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        public static bool IsDecimal(string inputData)
        {
            Match m = RegDecimal.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        public static bool IsDecimalSign(string inputData)
        {
            Match m = RegDecimalSign.Match(inputData);
            return m.Success;
        }

        #endregion

        #region 中文检测

        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);
            return m.Success;
        }

        #endregion

        #region 邮件地址
        /// <summary>
        /// 是否是邮箱
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }

        #endregion

        #region 电话,邮政编码,网络地址,手机号码,价格
        /// <summary>
        /// 验证是否是电话
        /// </summary>
        public static bool IsPhone(string inputDate)
        {
            if (!string.IsNullOrEmpty(inputDate))
            {
                Match m = RegTell.Match(inputDate);
                return m.Success;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 是否是邮政编码
        /// </summary> 
        public static bool IsSend(string inputDate)
        {
            if (!string.IsNullOrEmpty(inputDate))
            {
                Match m = RegSend.Match(inputDate);
                return m.Success;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 是否是网络地址
        /// </summary>
        public static bool IsUrl(string inputDate)
        {
            Match m = RegUrl.Match(inputDate);
            return m.Success;
        }
        /// <summary>
        /// 是否是手机号码
        /// </summary>
        public static bool IsMobilePhone(string inputDate)
        {
            Match m = RegMobilePhone.Match(inputDate);
            return m.Success;
        }
        /// <summary>
        /// 是否是价格
        /// </summary>
        public static bool IsMoney(string inputDate)
        {
            Match m = RegMoney.Match(inputDate);
            return m.Success;
        }
        #endregion
        #region 是否是时间格式
        /// <summary>
        /// 判断一个字符串是否时间格式
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDateTime(string inputData)
        {
            try
            {
                Convert.ToDateTime(inputData);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion
    }

2018-09-20 22:04:10 weixin_38591618 阅读数 1307
                    c# 字符串大小写转换

将字符串转换为大写
String 类有一个名为 ToUpper 的静态方法。 您可使用此方法将字符串转换为大写。例如:
string lower = “converted from lowercase”;
Console.WriteLine(lower.ToUpper());

将字符串转换为小写
ToLower 方法与 ToUpper 方法相反。 ToLower 将字符串转换为小写。例如:
string upper = “CONVERTED FROM UPPERCASE”;
Console.WriteLine(upper.ToLower());

c#字符串处理函数

阅读数 392

C#字符串的处理

阅读数 423

C#字符串处理的方法

博文 来自: Lin_For_Game
没有更多推荐了,返回首页