I have the following code, that is intended to loop through and add values to a string value.
Every other value, starting at index 0 of string builder, RepeatIndexes
, is supposed to always be a squiggly. and the other value from a specific index in a library I have elsewhere. Just pretend that
char InsertThis = indexJustForRepetas[IndexOfIndexes[RepeatTime]];
^-- ='s ' X ' --^
here's the actual code/loop:
StringBuilder RepeatIndexes = new StringBuilder("");
int ZeroPosition = 0; //for the indexes which will remain blank until the next loop-
int charPosition = 1;
int RepeatTime = 0; //1 thru final --^- 1^
while (NumberHalf > 0) //find and replace the char that was repeated within the string, 'AccountableToRepeats', with something that we can decipher later, during decryption-
{
RepeatIndexes.Insert(ZeroPosition, "~"); //inserting a squiggly line until next loop-
char InsertThis = indexJustForRepetas[IndexOfIndexes[RepeatTime]]; //find char at IndexOfIndexes to add into position-
RepeatIndexes.Insert (charPosition, InsertThis);
RepeatTime =RepeatTime +2;
ZeroPosition = ZeroPosition + 2;
NumberHalf = NumberHalf - 1;
}
the index for the squiggly lines ('~'), starts at 0: int ZeroPosition = 0;
The index for the characters ( "X" ), starts at 1: int charPosition = 1;
But for some reason the output I'm getting is: ~XXX~~
when it should be: ~X~X~X
is there something about the nature of string builder or insert()
I'm not understanding?
The loop looks like it should be increment correctly to be but the output just doesn't make any sense to me.
I hope this questions within the bounds of appropriateness for this service.
EDIT:
I think the problem is that charPosition
is not being updated. You need to update charPosition
with the same values as RepeatTime
and ZeroPosition
. So, add charPosition += 2;
in the while loop. What's happening is that 'X'
is always being inserted at position 1 (the position after the first ~
).
Also, you're over complicating it by using Insert
and all those indexes. RepeatTime
and ZeroPosition
have the same value so you don't need both.
You can use StringBuilder
's .Append()
to add text to the end of a string. I've used string interpolation ${var}
and assumed numberHalf = 3
but this should do what you want:
StringBuilder repeatIndexes = new StringBuilder();
int numberHalf = 3;
// int repeatTime = 0;
while (numberHalf > 0)
{
// replace below line with your char in array
char insertThis = 'X'; //indexJustForRepetas[IndexOfIndexes[repeatTime]];
repeatIndexes.Append($"~{insertThis}");
// repeatTime += 1 // needed for array call above. +1 or +2 depending on your intention
numberHalf = numberHalf - 1;
}
var outString = repeatIndexes.ToString();
output:
~X~X~X
You could split the line repeatIndexes.Append($"~{insertThis}")
into 2 if you prefer:
repeatIndexes.Append("~");
repeatIndexes.Append(insertThis);