大家好,所以我需要添加一个空间'在我显示的文本框中的每个字符之间。
我正在为用户提供一个类似于此He__o
的屏蔽词供他猜测,我想将其转换为H e _ _ o
我使用以下代码随机替换'_'
char[] partialWord = word.ToCharArray();
int numberOfCharsToHide = word.Length / 2; //divide word length by 2 to get chars to hide
Random randomNumberGenerator = new Random(); //generate rand number
HashSet<int> maskedIndices = new HashSet<int>(); //This is to make sure that I select unique indices to hide. Hashset helps in achieving this
for (int i = 0; i < numberOfCharsToHide; i++) //counter until it reaches words to hide
{
int rIndex = randomNumberGenerator.Next(0, word.Length); //init rindex
while (!maskedIndices.Add(rIndex))
{
rIndex = randomNumberGenerator.Next(0, word.Length); //This is to make sure that I select unique indices to hide. Hashset helps in achieving this
}
partialWord[rIndex] = '_'; //replace with _
}
return new string(partialWord);
我尝试过:partialWord[rIndex] = '_ ';
但这会带来错误&#34;文字中的字符太多&#34;
我尝试过:partialWord[rIndex] = "_ ";
然而这会返回错误&#34;无法将类型字符串转换为char。
我知道如何在每个角色之间实现空间吗?
由于
答案 0 :(得分:2)
由于结果字符串比原始字符串长,因此不能只使用一个字符数组,因为它的长度是常量。
这是StringBuilder
的解决方案:
var builder = new StringBuilder(word);
for (int i = 0 ; i < word.Length ; i++) {
builder.Insert(i * 2, " ");
}
return builder.ToString().TrimStart(' '); // TrimStart is called here to remove the leading whitespace. If you want to keep it, delete the call.
答案 1 :(得分:2)
以下代码应该按照您的要求执行。我认为代码是非常自我解释的,但是可以随意询问是否有任何关于代码的原因或方式的不清楚。
// char[] partialWord is used from question code
char[] result = new char[(partialWord.Length * 2) - 1];
for(int i = 0; i < result.Length; i++)
{
result[i] = i % 2 == 0 ? partialWord[i / 2] : ' ';
}
return new string(result);