简体   繁体   English

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

[英]Replace each character of string with new character string

The c# program I'm developing checks the first character of user input and if it starts with . 我正在开发的c#程序会检查用户输入的第一个字符,以及是否以开头. (dot) I want to replace each character of user input with pacified character string while the user is writing, but I'm getting the error (点)我想在用户书写时用和平的字符串替换用户输入的每个字符,但出现错误

Index out of bounds exception 索引超出范围异常

My code: 我的代码:

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

You're overrunning the bounds of the string, replace: 您超出了字符串的界限,请替换:

while (x <= MyText.Length) {

with

while (x < MyText.Length) {
while(x < MyText.Length)

or 要么

while(x <= MyText.Length - 1)

If array has length = x, its last index is x-1, because array starts from 0 index 如果数组的长度为x,则其最后一个索引为x-1,因为数组从0索引开始

If I understand you right (there're no samples in question), I suggest using Linq which is straitforward; 如果我理解正确(没有问题的样本),我建议使用straitforward的Linq try using modular arimethics - index % MyText.Length to avoid index problems 尝试使用模块化算术 - index % 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;

Outcome: 结果:

   Hello WorldHello WorldHello

First of all as @Daniell89 said: 首先如@ Daniell89所说:

use 采用

while(x < MyText.Length)

Secondly: You use x as an index not only for MyText but for textBox1.Text too. 其次:您不仅将x用作MyText的索引,还将x用作textBox1.Text的索引。 So you need to check that it is long enough. 因此,您需要检查它是否足够长。

you can do something like this: 您可以执行以下操作:

while (x < Math.Min(MyText.Length, textBox1.Text.Length)
{
    NewText = textBox1.Text.Replace(textBox1.Text[x], MyText[x]);
    TextBox1.Text = NewText;
    x++;
}

But I think it would be better to use for statement here. 但是我认为最好在这里进行陈述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM