最近碰到一個這樣的需求,字符串指定間隔長度插入指定字符串,大概描述一下
有一字符串 “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