0

I have the following code :

String[] enteteSplit = new String[48];
enteteSplit = entete.Split(';');
enteteSplit[35] = enteteSplit[35].Replace(',', '.');

Where entete is a string. The 3rd line is throwing an IndexOutOfRangeException and i couldn't resolve this, any ideas ?

Thanks a lot.

3
  • 1
    Well, it appears there are less than 36 items in enteteSplit. Commented Feb 10, 2015 at 15:16
  • 1
    enteteSplit has less than 36 items in it. Your first line doesn't matter since Split() just returns a new array. Commented Feb 10, 2015 at 15:16
  • I also tried doing : String[] enteteSplit = entete.Split(';'); enteteSplit[35] = enteteSplit[35].Replace(',', '.'); And i checked that 'entete' had more than 35 ';' and it is still not working. I also checked that 'enteteSplit[35]' had something in it. Commented Feb 10, 2015 at 15:27

1 Answer 1

3

When you call this line

enteteSplit = entete.Split(';');

you are effectively creating an array that contains no more 48 elements but just the elements obtained splitting the string at the semicolon character.

So if your string is

entete = "test;test1;test2";
enteteSplit = entete.Split(';');

the resulting array has only 3 elements and thus trying to reach the 35th element causes the IndexOutOfRange Exception

You need to introduce a safety check here

if(enteteSplit.Length > 35)
   enteteSplit[35] = enteteSplit[35].Replace(',', '.');
Sign up to request clarification or add additional context in comments.

1 Comment

It seems that adding the safety check has resolved my problem. Thank you :)

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.