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.

Recommended Answers

All 9 Replies

Hi,

Hope this helps. :)

string mystring = "system\admin";
int slash_position = mystring.IndexOf("\");
string string1 = mystring.substring(0,slash_position-1);
string string2 = mystring.substring(slash_position,mystring.length-1);

Regards

commented: complete fail -1
commented: N/A +6

Hi,

Hope this helps. :)

string mystring = "system\admin";
int slash_position = mystring.IndexOf("\");
string string1 = mystring.substring(0,slash_position-1);
string string2 = mystring.substring(slash_position,mystring.length-1);

Regards

Hi,

Thanks for your reply. I'm getting an error called "Newline in constant" in this line "int slash_position = mystring.IndexOf("\");"

Ah, the \ is a special character. Try

int slash_position = mystring.IndexOf("\\");

Do you need to use the IndexOf member?

There are members that can more easily split strings seperated by special characters...

Do you need to use the IndexOf member?

There are members that can more easily split strings seperated by special characters...

Ah, the \ is a special character. Try

int slash_position = mystring.IndexOf("\\");

I'm getting an ArgumentOutOfRange Exception. "Length cannot be less than zero.
Parameter name: length"

Try understanding what the code does. This will allow you to find the fault. I suspect that I have made some stupid error in it, which you can easily figure out... :)

private void button1_Click(object sender, EventArgs e)
    {
      string domainAndUser = @"system\admin";
      string[] sArray = domainAndUser.Split(new char[] { '\\' }, StringSplitOptions.None);
      string domain = sArray[0];
      string user = sArray[1];
      Console.WriteLine("Domain: " + domain);
      Console.WriteLine("User: " + user);
    }

Results in:

Domain: system
User: admin
commented: Efficient as always! +5
commented: lol StringSplitOptions.None +6

Try understanding what the code does. This will allow you to find the fault. I suspect that I have made some stupid error in it, which you can easily figure out... :)

Bah, I meant to uprep this post with "complete win" while downrepping the first, but forgot you could only rep somebody once per day. :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.