字符串操作是C#中最基本的、最常见的、也是用的最多的,以下我总结 了几种常见的方法
1.把字符串按照分隔符转换成 List
/// <summary> /// 把字符串按照分隔符转换成 List /// </summary> /// <param name="str">源字符串</param> /// <param name="speater">分隔符</param> /// <param name="toLower">是否转换为小写</param> /// <returns></returns> public static List<string> GetStrArray(string str, char speater, bool toLower) { var list = new List<string>(); var ss = str.Split(speater); foreach (var s in ss) { if (string.IsNullOrWhiteSpace(s) || s == speater.ToString(CultureInfo.InvariantCulture)) continue; var strVal = s; if (toLower) { strVal = s.ToLower(); } list.Add(strVal); } return list; }
2.把字符串转 按照, 分割 换为数据
/// <summary> /// 把字符串转 按照, 分割 换为数据 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string[] GetStrArray(string str) { return str.Split(new[] { ‘,‘, ‘,‘ }); }
3.得到数组列表以逗号分隔的字符串
/// <summary> /// 得到数组列表以逗号分隔的字符串 /// </summary> /// <param name="list"></param> /// <param name="speater"></param> /// <returns></returns> public static string GetArrayStr(List<string> list, string speater) { var sb = new StringBuilder(); for (var i = 0; i < list.Count; i++) { if (i == list.Count - 1) { sb.Append(list[i]); } else { sb.Append(list[i]); sb.Append(speater); } } return sb.ToString(); }
4.得到字符串长度
/// <summary> /// 得到字符串长度 /// </summary> /// <param name="inputStr"></param> /// <returns></returns> public static int StrLength(string inputStr) { var asc = new ASCIIEncoding(); var s = asc.GetBytes(inputStr); return s.Sum(t => t == 63 ? 2 : 1); }
5.截取指定长度字符串
/// <summary> /// 截取指定长度字符串 /// </summary> /// <param name="inputString"></param> /// <param name="len"></param> /// <returns></returns> public static string CutStr(string inputString, int len) { var isShowFix = false; if (len % 2 == 1) { isShowFix = true; len--; } var ascii = new ASCIIEncoding(); var tempLen = 0; var tempString = ""; var s = ascii.GetBytes(inputString); for (var i = 0; i < s.Length; i++) { tempLen += s[i] == 63 ? 2 : 1; try { tempString += inputString.Substring(i, 1); } catch { break; } if (tempLen > len) break; } var mybyte = Encoding.Default.GetBytes(inputString); if (isShowFix && mybyte.Length > len) tempString += "…"; return tempString; }
暂时就这五种方法了。
时间: 2024-10-10 09:19:43