Monday, March 26, 2012

string.trimstart()

I got to be something stupid, but for some reason I can get this code to work:

string username = HttpContext.Current.User.Identity.Name.ToString();char[] MyChar = {' ','\\'}; Login1.UserName = username.TrimStart(MyChar);

I want to trim the \ of: MAINOFFICE\username

Thanks,

Erick

Can you use :

username.Replace(@."\","");
TrimStart removes all the occurances from the beginning of the instance. "\" appears in the middle of the string.
string username ="MAINOFFICE\\username";

txtOutput.Text = username.Remove(0, username.LastIndexOf("\\") + 1);

that will work, assuming that usernames cant have the \ in them :P


keyboardcowboy:

username.LastIndexOf("\\")

Won't that just give the last index of the string?


I'm sorry. What I mean to said was I want to trim everything before the \, but sometimes it might not be MAINOFFICE thats the problem I'm having. I just want the username.


bullpit:

keyboardcowboy:

username.LastIndexOf("\\")

Won't that just give the last index of the string?

yes, but doing remove(0, LastIndexOf("\\")) will remove all characters from position 0 until the last \. and in this case it seems like the last character before the username will always be \. :)

This should work for the user who posted this question ... i think :P


username.Replace(username.Substring(0,username.LastIndexOf(@."\")+1),"");

Dim userStringAs String ="MAINOFFICE\userName"Dim userNameAs String = userString.SubString(userString.IndexOf("\") + 1)
Just make sure you use your @."\" in C# or "\\"

keyboardcowboy:

bullpit:

keyboardcowboy:

username.LastIndexOf("\\")

Won't that just give the last index of the string?

yes, but doing remove(0, LastIndexOf("\\")) will remove all characters from position 0 until the last \. and in this case it seems like the last character before the username will always be \. :)

This should work for the user who posted this question ... i think :P

yep, it worked like a charm for me.

Thanks


keyboardcowboy-

You are right, but may be I took OP's problem too seriously. He mentioned that he wanted to remove "\" until his last post. Your solution works. I unnecessarily gave a longer method with replace to remove all the characters before "\" in my last post. Ignore all crap that I post.


haha, yeah at first i thought he meant what you were showing to do, but I kinda figured he wanted only the user name.

now he has a handlefull of string altering techniques though :)


thanks guys. I'm sorry for the mess, was my bad.Embarrassed

0 comments:

Post a Comment