Link to home
Start Free TrialLog in
Avatar of ASPDEV
ASPDEV

asked on

Substring in C#

I'm getting this error, when I tried substring a string.

Index and length must refer to a location within the string.
Parameter name: length



string str = "CHECK THIS|I NEED TO SHOW THIS.||"

From the above string I need to parse the string start from Pipe(|) and end with double Pipe(||).

str = str.Substring(str.IndexOf("|") + 1, str.IndexOf("||")-1);

Also tried this:
str = str.Substring(str.IndexOf("|") + 1, str.Length-3);
SOLUTION
Avatar of Ron Malmstead
Ron Malmstead
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ASPDEV
ASPDEV

ASKER

xuserx2000,

Thanks for quick response I can with split, but what's wrong with my code.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ASPDEV

ASKER

Thanks.
The second parameter of substring is length, so it is the number of characters you want to retrieve after the character position you are starting at (i.e. the first parameter).
So you need to subtract the start postition from the second parameter:

int startpos = str.IndexOf("|") + 1;
int endpos =  str.IndexOf("||") - startpos;
str = str.Substring(startpos, endpos);