Share via


string.Split() in C#

Question

Tuesday, October 20, 2009 8:54 AM

I have a string like "system\admin". Now I want get the "admin" part alone from the string using Split() method in C#. I have tried many ways but I'm not able to get it.Can anyone please help me out.Thank you.

All replies (6)

Tuesday, October 20, 2009 9:29 AM ✅Answered | 1 vote

**try this way **

**
**

String s=@"System\admin";

string[] words = s.Split('\');

foreach (string word in words)

{

**   TextBox1.Text = word.ToString();**

}


Tuesday, October 20, 2009 9:49 AM ✅Answered

ok then you can also do it like below in two ways:

string str = @"system\admin";
string[] arr = str.Split(@"\".ToCharArray());
string result = arr[1];

//or

string result2 = str.Substring(str.IndexOf(@"\") + 1);

"\ is a special character. You can have more detailed information @

http://en.csharp-online.net/Manipulating_Strings_in_CSharp%E2%80%94Using_Escape_Characters


Tuesday, October 20, 2009 10:14 AM ✅Answered

Hi,
For getting admin part only it will help you.

string s = @"System\Admin";
            string a=s.Substring(s.IndexOf(@"\")+1);
            MessageBox.Show(a);

Best Regards, C.Gnanadurai Please mark the post as answer if it is helpfull to you


Tuesday, October 20, 2009 9:04 AM

hi,

string str = "system\\admin";
            string[] arr = str.Split("\\".ToCharArray());
            string result = arr[1];

//or

string result2 = str.Substring(str.IndexOf("\\") + 1);

isil


Tuesday, October 20, 2009 9:20 AM

Hi,

   My string has only '\ symbol and not '\'.


Tuesday, October 20, 2009 1:06 PM | 2 votes

Hi,

   My string has only '\ symbol and not '\'.

The backslash is an escape character.  And, in traditional syntax, to get an actual backslash character you must escape it using another backslash, or use the verbatim string literal syntax (by preceding the double quotes with the @ character)

string backslash4 = "\";
string backslash4 = @"\;
char backslash = '\';

note, there is no equivalent verbatim @ syntax for character literals in C#

See docs for string literals and character literals .

So I would use this:

string s = @"system\admin";
string[] words = s.Split('\');