Last post Oct 20, 2009 09:40 PM by Paul Linton
Oct 20, 2009 04:43 AM|scvinod|LINK
I have a string like "system\admin". Now I want get the "admin" part alone from the string using IndexOf() method.Can anyone please help me out.Thank you.
Oct 20, 2009 06:51 AM|DeadBurger|LINK
string s = "system\admin";
s = s.Substring(s.indexOf("\") + 1, s.Length - s.indexOf("\") - 1);
Or you could use a regex like this:
Match m = Regex.Match(s, ".+\\(.+)");
string afterSlash = m.Groups.Value;
Oct 20, 2009 06:54 AM|Paul Linton|LINK
How about using Split?
string username = fullName.Split('\\');
This will give you the piece after the \ character.
Oct 20, 2009 08:26 AM|scvinod|LINK
Thanks for your reply.I tried your method.I'm getting this exception "Index was outside the bounds of the array."
Oct 20, 2009 08:30 AM|Paul Linton|LINK
In that case your string doesn't have a '\' character in it. Have you done any debugging? Single stepping and examining variables is a very useful skill.
Oct 20, 2009 08:53 AM|devensawant|LINK
make use of following code it will give you exactly last substring after \ even if your original string contains more than one \
string splitarray = fullName.Split(@"\".ToCharArray());
Oct 20, 2009 09:04 AM|scvinod|LINK
Hi Paul Linton,
I did exactly what you provided me as an example. Here is the sceen shot of the coding along with the exception mark.Thanks for your reply.
Oct 20, 2009 09:19 AM|devensawant|LINK
use the following code
string fullName = @"system\admin";
string username = fullName.Substring(i+1, fullName.Length - (i+1));
Oct 20, 2009 09:24 AM|scvinod|LINK
Hi Deven Sawant,
I have tried your method and it works.But the problem is I'm actually getting the string value from the database which will have '\' symbol. SO, I can't declare it as string s=@"system\admin";
Oct 20, 2009 09:40 AM|scvinod|LINK
It's working now.Thanks a lots.
Oct 20, 2009 10:23 AM|devensawant|LINK
Please mark it as answer so it will help other how has same problem
Oct 20, 2009 09:40 PM|Paul Linton|LINK
The code in your screen shot does not have a '\' character in it, you have the '\a' character which is an alert. To put a '\' character in a literal string you need to repeat the '\' charcter "system\\user"