0

The c# program I'm developing checks the first character of user input and if it starts with . (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++;
    }
}
1
  • 2
    x<=MyText.Length goes out of bounds. Arrays are 0 indexed. Commented Mar 27, 2017 at 11:17

4 Answers 4

3

You're overrunning the bounds of the string, replace:

while (x <= MyText.Length) {

with

while (x < MyText.Length) {
Sign up to request clarification or add additional context in comments.

Comments

2
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

1 Comment

@Elias You should check textBox1.Text.Length also.
1

If I understand you right (there're no samples in question), I suggest using Linq which is straitforward; try using modular arimethics - index % MyText.Length to avoid index problems

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

Comments

0

First of all as @Daniell89 said:

use

while(x < MyText.Length)

Secondly: You use x as an index not only for MyText but for textBox1.Text too. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.