C# adding a character in a string

后端 未结 8 1889
长情又很酷
长情又很酷 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:28

    I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

    ts = ts.Insert(6,".");
    ts = ts.Insert(4,":");
    ts = ts.Insert(2,":");
    

    Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

    You could try something similar by doing:

    alpha = alpha.Insert(5,"-");
    alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
    alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
    ...
    

提交回复
热议问题