如何在C#中每X个特定字符添加一个char

时间:2012-12-17 15:14:15

标签: c# string line

我需要一个在15'之后添加换行符的提示,

喜欢那样

db 4Dh, 5Ah, 80h, 00h, 01h, 00h, 00h, 00h, 04h, 00h, 10h, 00h, 0FFh, 0FFh, 00h, <-- return line here

2 个答案:

答案 0 :(得分:1)

这应该让你朝着正确的方向前进:

string myString = "db 4Dh, 5Ah, 80h, 00h, 01h, 00h, 00h, 00h, 04h, 00h, 10h, 00h, 0FFh, 0FFh, 00h, db 4Dh, 5Ah, 80h, 00h, 01h, 00h, 00h, 00h, 04h, 00h, 10h, 00h, 0FFh, 0FFh, 00h";
StringBuilder sb = new StringBuilder();
string[] splitString = myString.Split(',');
for (int idx = 0; idx < splitString.Length; idx++)
{
    sb.Append(splitString[idx] + ",");
    if (idx > 0 && idx%15 == 0)
    {
        sb.Append('\n');
    }
}
string output = sb.ToString();

答案 1 :(得分:0)

StringBuilder方法的替代方案:

static class StringExt
{
    public static string InsertAfterEvery(
        this string source, string insert, int every, string find)
    {
        int numberFound = 0;
        int index = 0;
        while (index < source.Length && index > -1)
        {
            index = source.IndexOf(find, index) + find.Length;
            numberFound++;
            if (numberFound % every == 0)
            {
                source = source.Insert(index, insert);
                index += insert.Length;
            }
        }
        return source;
    }
}

// I used 3 rather than 15
Console.WriteLine(
    "db 4Dh, 5Ah, 80h, 00h, 01h, 00h, 00h, 00h, 04h,".InsertAfterEvery(
        Environment.NewLine, 3, ","));