简体   繁体   中英

How to append every X in c# stringbuilder

I'm using unity and c# and am not sure how to use stringbuilder to append a "/" every X characters. I have code and can build a string from a array with the code below, and add a comma after each string, but i need to add the "/" after every x string

it should for example convert "122342" to "1,2,2,/,3,4,2". Currently it would convert it to "1,2,2,3,4,2" this is the code i have already

StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){

    Builtstring.Append(griditem).Append(",");

}
built = Builtstring.ToString();

Use a FOR loop and then check if the character is a factor of some desired nTH character. If so add an extra '/'.

        int x = 2; // your x
        StringBuilder builtstring = new StringBuilder();
        for (int i = 0; i < tobuild.Length; i++) 
        { 
            string item = tobuild[i];
            builtstring.Append(item).Append(",");
            if (i%x==0) { builtstring.Append("/"); }

        }
        string built = builtstring.ToString();

You can iterate over the array of strings using a for loop, which provides an index.
For each iteration, add the current String to the StringBuilder , in addition to a ',' in case we still didn't reach the last string in the array.
Also, after x strings add a '/'. We can know that we reached x strings using the % (modulus) operator.
Notice that I start the loop from index = 1. I do that because the modulus operator for the value 0 with any positive number will yield 0, which will add the '/' char after the first word, something that we don't necessarily want.

static void Insert(StringBuilder b, int x, string[] tobuild)
{
    for(var index = 1; index < tobuild.Length; ++index)
    {   
        b.Append(tobuild[index]);

        if(index != tobuild.Length -1)
        {
            b.Append(",");
        }

        if(0 == index % x)
        {
            b.Append("/");
        }
    }
}

Add an if statement to evaluate the character and then act accordingly.

StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(griditem == 'x') { Builtstring.Append(griditem).Append(@"/"); }
Builtstring.Append(griditem).Append(",");

}
built = Builtstring.ToString();

Or if you actually want to count a certain number of characters before putting a slash you can do this.

int count = 10;
int position = 0;
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(position == count) { Builtstring.Append(griditem).Append(@"/"); position = 0; }
else{Builtstring.Append(griditem).Append(","); position++;}}
built = Builtstring.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM