string search...

Hi,
I need to get a SubString from a string but the SubString length can change and also the start position of the SubString can be changed.
The string that starts with "<User" and ends withe "</User>" (i need to get the string between them).
Any Idea?
Thanks
 
LVL 1
udirAsked:
Who is Participating?
 
JimBrandleyCommented:
You can do this:
int startPos = yourString.IndexOf(""<User");
int endPos = yourString.IndexOf("</User>" );
if ((startPos > -1) && (endPos > -1))
{
   startPos += 5;
   string middle = yourString.SubString( startPos, endPos - startPos);
}

Jim
0
 
udirAuthor Commented:
Hi,
Thanks, just for knoledge :
what is the meanning of :
startPos += 5;
0
 
JimBrandleyCommented:
yourString.IndexOf("<User"); returns the start location of this string in the string you are searching. So, say the whole string is:

<User>Tom</User>

Then startPos is returned as zero. By adding 5 to startPos, we are preparing to get the substring that starts with ">".

BTW:

startPos += 5;

is a shorthad way of writing:
startPos = startPos + 5;

If you wanted to skip the ">" too, and just get "Tom", change the 5 to a 6.

Jim
0
 
udirAuthor Commented:
OK, Thanks a lot
0
 
JimBrandleyCommented:
My pleasure. Good luck.

Jim
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.