插入子字符串不会插入索引

时间:2018-12-15 02:39:49

标签: c# while-loop insert stringbuilder

我有以下代码,旨在循环遍历并将值添加到字符串值。 从字符串生成器RepeatIndexes的索引0开始的所有其他值应该始终是弯曲的。另一个值来自我在其他地方拥有的库中特定索引的值。只是假装

char InsertThis = indexJustForRepetas[IndexOfIndexes[RepeatTime]];  

^-=的'X'-^

这是实际的代码/循环:

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;
}

波浪线('〜')的索引始于0:int ZeroPosition = 0;

字符(“ X”)的索引从1开始:int charPosition = 1;

但是由于某种原因,我得到的输出是:~XXX~~

应为~X~X~X

关于字符串生成器或insert()的性质我是否不了解? 循环看起来应该正确地递增,但是输出对我来说没有任何意义。

我希望这个问题在适用于此服务的范围内提出。

1 个答案:

答案 0 :(得分:1)

编辑:

我认为问题在于charPosition未被更新。您需要使用与charPositionRepeatTime相同的值来更新ZeroPosition。因此,在while循环中添加charPosition += 2;。发生的情况是,'X'始终插入位置1(第一个~之后的位置)。

此外,您还使用Insert和所有这些索引来使其复杂化。 RepeatTimeZeroPosition的值相同,因此您不需要两者。

您可以使用StringBuilder的{​​{1}}将文本添加到字符串的末尾。我使用了字符串插值.Append()并假定了${var},但这应该可以满足您的要求:

numberHalf = 3

如果愿意,您可以将行 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 分成2个

repeatIndexes.Append($"~{insertThis}")
相关问题