0

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();
Thomas Hilbert
  • 3,559
  • 2
  • 13
  • 33
Aboar
  • 5
  • 5

3 Answers3

1

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();
Cody Popham
  • 992
  • 5
  • 14
0

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("/");
        }
    }
}
m1o2
  • 1,549
  • 2
  • 17
  • 27
0

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();