0

I have to check the condition in asp.net for string array

The conditions is I can either have two values 360__image.jpg and image.jpg.
I have to return the correct value from the condition

  1. If the string has 360_image.jpg I have to return only image.jpg and cutting 360_
  2. If the string is image.jpg I have to return the same image.jpg

Code

public string splitString(string str)
{
   string[] FileName = str.Split('_');   
   if (FileName[2] != "")
   {
       return FileName[2];
   }
   else
   {
        return FileName[0];
   }
}

The problem with above code is I am getting the error

Index was outside the bounds of the array
1
  • It's not clear. Is 360__ fixed for any "image.jpg"? If so replace it with an empty string. I'm assuming "image" could be a different string every time but not the prefix. Commented May 22, 2013 at 6:24

3 Answers 3

2

You should check for length before accessing element from the array, that is why you are getting the exception, since split probably resulted in array of two elements.

Not exactly sure about your requirement but I think you can simplify your method as:

public string splitString(string str)
{
    if (str.Contains("_")) //or check for 360__
        return str.Substring(str.LastIndexOf('_') + 1); 
    else
        return str;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting as _image001.png
@Anish, try return str.Substring(str.LastIndexOf('_') + 1);
1

You can use LastIndexOf:

public string splitString(string str)
{
    return str.Substring(str.LastIndexOf('_') + 1);
}

Or even use LINQ Last:

public string splitString(string str)
{
    return str.Split('_').Last();
}

2 Comments

here the string can either have 360_image.jpg or image.jpg so we need the condition to checked for the above answer
@Anish: you don't need actually, it still works and the code is simpler
0

Array has 2 elements , means idexes 0 and 1.

But you have taken into your code as FileName[2] .

This 2nd index may be wrong thats why error is comming. It may be 1.

Try with:

public string splitString(string str)
    {

        string[] FileName = str.Split('_');   

        if (FileName[1] != "")
        {
            return FileName[1];
        }
        else
        {
            return FileName[0];
        }
    }

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.