Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用新字符串替换字符串的每个字符_C# - Fatal编程技术网

C# 用新字符串替换字符串的每个字符

C# 用新字符串替换字符串的每个字符,c#,C#,我正在开发的c程序检查用户输入的第一个字符,以及它是否以开头。dot我想在用户写入时用压缩字符串替换用户输入的每个字符,但我得到了错误 索引越界异常 我的代码: if (textBox1.Text.StartWith(".")) { string MyText = "Hello World"; int x = 0; string NewText; while (x <= MyText.Length) { NewText = textBox1.

我正在开发的c程序检查用户输入的第一个字符,以及它是否以开头。dot我想在用户写入时用压缩字符串替换用户输入的每个字符,但我得到了错误

索引越界异常

我的代码:

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。