C# 用新字符串替换字符串的每个字符
我正在开发的c程序检查用户输入的第一个字符,以及它是否以开头。dot我想在用户写入时用压缩字符串替换用户输入的每个字符,但我得到了错误 索引越界异常 我的代码:C# 用新字符串替换字符串的每个字符,c#,C#,我正在开发的c程序检查用户输入的第一个字符,以及它是否以开头。dot我想在用户写入时用压缩字符串替换用户输入的每个字符,但我得到了错误 索引越界异常 我的代码: if (textBox1.Text.StartWith(".")) { string MyText = "Hello World"; int x = 0; string NewText; while (x <= MyText.Length) { NewText = textBox1.
if (textBox1.Text.StartWith(".")) {
string MyText = "Hello World";
int x = 0;
string NewText;
while (x <= MyText.Length) {
NewText = textBox1.Text.Replace(textBox1.Text[x], MyText[x]);
TextBox1.Text = NewText;
x++;
}
}
您超出了字符串的边界,请替换:
while (x <= MyText.Length) {
与
您超出了字符串的边界,请替换:
while (x <= MyText.Length) {
与
或
若数组的长度为x,则其最后一个索引为x-1,因为数组从0索引开始
或
如果数组的长度=x,它的最后一个索引是x-1,因为数组从0索引开始如果我正确理解您的意思,那么我建议使用Linq,它是straitforward;尝试使用模块化arimethics-索引%MyText.Length以避免索引问题
string source = ".My Secret Message for Test";
string MyText = "Hello World";
// If user input starts with dot
if (source.StartsWith("."))
source = string.Concat(source
.Select((c, index) => MyText[index % MyText.Length]));
TextBox1.Text = source;
结果:
Hello WorldHello WorldHello
如果我理解你的话,没有问题的样本,我建议使用Linq,这是一种限制;尝试使用模块化arimethics-索引%MyText.Length以避免索引问题
string source = ".My Secret Message for Test";
string MyText = "Hello World";
// If user input starts with dot
if (source.StartsWith("."))
source = string.Concat(source
.Select((c, index) => MyText[index % MyText.Length]));
TextBox1.Text = source;
结果:
Hello WorldHello WorldHello
首先,正如@Daniell89所说: 使用 第二: 您不仅将x用作MyText的索引,还将x用作textBox1.Text的索引。所以你需要检查它是否足够长 您可以这样做:
while (x < Math.Min(MyText.Length, textBox1.Text.Length)
{
NewText = textBox1.Text.Replace(textBox1.Text[x], MyText[x]);
TextBox1.Text = NewText;
x++;
}
但我认为最好在这里使用这个语句。首先,正如@Daniell89所说: 使用 第二: 您不仅将x用作MyText的索引,还将x用作textBox1.Text的索引。所以你需要检查它是否足够长 您可以这样做:
while (x < Math.Min(MyText.Length, textBox1.Text.Length)
{
NewText = textBox1.Text.Replace(textBox1.Text[x], MyText[x]);
TextBox1.Text = NewText;
x++;
}
但我认为在这里使用for语句会更好xx@Elias您还应该检查textBox1.Text.Length。@Elias您还应该检查textBox1.Text.Length。