3

I have a string like '/Test1/Test2', and i need to take Test2 separated from the same. How can i do that in c# ?

1
  • 1
    look at the string.Split() method. Commented Sep 27, 2011 at 13:52

7 Answers 7

4

Try this:

string toSplit= "/Test1/Test2";

toSplit.Split('/');

or

toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries);

to split, the latter will remove the empty string.

Adding .Last() will get you the last item.

e.g.

toSplit.Split('/').Last();
Sign up to request clarification or add additional context in comments.

1 Comment

SplitOptions.RemoveEmptyEntries :P or something like that I forget the exact name, to get rid of the empty you would get because of the first /
2

Use .Split().

string foo = "/Test1/Test2";
string extractedString = foo.Split('/').Last(); // Result Test2

This site have quite a few examples of splitting strings in C#. It's worth a read.

Comments

2

Using .Split and a little bit of LINQ, you could do the following

string str = "/Test1/Test2";
string desiredValue = str.Split('/').Last();

Otherwise you could do

string str = "/Test1/Test2";
string desiredValue = str;
if(str.Contains("/"))
   desiredValue = str.Substring(str.LastIndexOf("/") + 1);

Thanks Binary Worrier, forgot that you'd want to drop the '/', darn fenceposts

1 Comment

Possibly string desiredValue = str.Substring(str.LastIndexOf("/")+1); because you don't want the seperator?
1

string[] arr = string1.split('/'); string result = arr[arr.length - 1];

Comments

1
string [] split = words.Split('/');

This will give you an array split that will contain "", "Test1" and "Test2".

Comments

1

If you just want the Test2 portion, try this:

string fullTest = "/Test1/Test2";
string test2 = test.Split('/').ElementAt(1);  //This will grab the second element.

Comments

0
string inputString = "/Test1/Test2";
            string[] stringSeparators = new string[] { "/Test1/"};
            string[] result;
            result = inputString.Split(stringSeparators,
                      StringSplitOptions.RemoveEmptyEntries);

                foreach (string s in result)
                {
                    Console.Write("{0}",s);

                }


OUTPUT : Test2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.