C# adding a character in a string

后端 未结 8 1808
长情又很酷
长情又很酷 2021-01-04 06:56

I know I can append to a string but I want to be able to add a specific character after every 5 characters within the string

from this string alpha = abcdefghijklmno

相关标签:
8条回答
  • 2021-01-04 07:44

    You can use this:

    string alpha = "abcdefghijklmnopqrstuvwxyz";
    int length = alpha.Length;
    
    for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
    {
        alpha = alpha.Insert(i, "-");
    }
    

    Works perfectly with any string. As always, the size doesn't matter. ;)

    0 讨论(0)
  • 2021-01-04 07:52

    Inserting Space in emailId field after every 8 characters

    public string BreakEmailId(string emailId) {
        string returnVal = string.Empty;
        if (emailId.Length > 8) {           
            for (int i = 0; i < emailId.Length; i += 8) {
                returnVal += emailId.Substring(i, 8) + " ";
            }
        }
    
        return returnVal;
    }
    
    0 讨论(0)
提交回复
热议问题