C# 字串每隔 n 個字元插入字串

string mFunc(string strIn, int number, string insertStr)
{
    string strNew = string.Empty;
    for (int i = 0; i < strIn.Length; i++)
    {
        if ((i + 1) % interval == 0 && (i + 1) < strIn.Length) // 判斷是否被間隔整除且不是最後一位
            strNew += strIn[i] + insertStr;
        else
            strNew += strIn[i];
        //三元寫法
        //strNew += ((i + 1) % interval == 0 && (i + 1) < strIn.Length) ? strIn[i].ToString() + insertStr : strIn[i].ToString();
     }
     return strNew;
}

string mFunc(string strIn, int interval, string insertStr)
{
    for (int i = interval; i < strIn.Length; i += interval + insertStr.Length)
        strIn = strIn.Insert(i, insertStr);
    return strIn;
}

發佈留言