Reputation: 39
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++;
}
}
Upvotes: 0
Views: 142
Reputation: 186688
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
Upvotes: 1
Reputation: 825
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.
Upvotes: 0
Reputation: 2272
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
Upvotes: 2
Reputation: 8991
You're overrunning the bounds of the string, replace:
while (x <= MyText.Length) {
with
while (x < MyText.Length) {
Upvotes: 3