/// <summary> /// 将指定字符串按指定长度进行剪切, /// </summary> /// <param name= "oldStr "> 需要截断的字符串 </param> /// <param name= "maxLength "> 字符串的最大长度 </param> /// <param name= "endWith "> 超过长度的后缀 </param> /// <returns> 如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串 </returns> public static string StringTruncat(string oldStr, int maxLength, string endWith) { if (string.IsNullOrEmpty(oldStr)) // throw new NullReferenceException( "原字符串不能为空 "); return oldStr + endWith; if (maxLength < 1) throw new Exception("返回的字符串长度必须大于[0] "); if (oldStr.Length > maxLength) { string strTmp = oldStr.Substring(0, maxLength); if (string.IsNullOrEmpty(endWith)) return strTmp; else return strTmp + endWith; } return oldStr; }
NET中生成指定长度的随机字符串
1、生成指定长度的随机数字串
2、生成指定长度的随机字符串(包括是否大小写)
Console.Write(RndStr(5));//测试随机数字串 Console.Write(RndStr(5,true));//true:表示大写;false:表示小写 Console.ReadKey();
/// <summary> /// 生成指定长度的随机数字串 ///</summary> ///<param name="length">长度</param> ///<returns></returns> static string RndStr(int length) { Random rnd = new Random(); string returnstring = ""; int i=1; while (i <=length) { returnstring +=rnd.Next(0,9).ToString(); i++; } return returnstring; } ///<summary> /// 生成指定长度的随机字符串 ///</summary> ///<param name="length">长度</param> ///<param name="IsUpper">是否大写</param> ///<returns></returns> static string RndStr(int length, bool IsUpper) { Random rnd = new Random(); string returnstring = ""; int i = 1; if (IsUpper) { while (i <= length) { returnstring += ((char)rnd.Next (65, 91)).ToString(); i++; } } else { while (i <= length) { returnstring += ((char)rnd.Next (97, 122)).ToString(); i++; } } return returnstring; }