最近碰到一个这样的需求,字符串指定间隔长度插入指定字符串,大概描述一下
有一字符串 “abcde12345fghig67890” ,我想指定间隔长度为5(这个是字符串长度能够被5整除),插入“/”字符串(字符串不限制长度)。
最后返回结果“abcde/12345/fghig/67890” .
下面是我实现此功能代码,贴出来与大家讨论,我觉得写法太繁琐,看大家有没有更好实现方法。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleStringSplitPlusSpecialChar { class Program { static void Main(string[] args) { var originalValue = "abcde12345fghig67890"; var splitLength = 5; var splitSpecialString = "/"; var targetValue = SplitStringPlusSpecialString(originalValue, splitLength, splitSpecialString); Console.Write(targetValue); Console.Read(); } public static string SplitStringPlusSpecialString(string originalValue, int splitLength, string splitSpecialString) { var originalLength = originalValue.Length; var splitCount = originalLength / splitLength; var targetValue = originalValue; var splitSpecialStringLength = splitSpecialString.Length; for (var i = 0; i < splitCount; i++) { targetValue = targetValue.Insert((i + 1) * splitLength + (i * splitSpecialStringLength), splitSpecialString); } return targetValue.TrimEnd(splitSpecialString.ToCharArray()); } } }
源代码下载: http://files.cnblogs.com/files/davidzhou/DemoSolution.zip
时间: 2024-12-23 13:34:23