Pradeep
Pradeep

Reputation: 4872

How to split string using Substring

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

Upvotes: 3

Views: 20146

Answers (7)

Chandan Kumar
Chandan Kumar

Reputation: 318

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

Upvotes: 0

Dan McClain
Dan McClain

Reputation: 11920

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

Upvotes: 2

Coding Flow
Coding Flow

Reputation: 21881

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();

Upvotes: 4

WEFX
WEFX

Reputation: 8572

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.

Upvotes: 1

Rendijs S
Rendijs S

Reputation: 365

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

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

Upvotes: 1

aamir
aamir

Reputation: 151

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

Upvotes: 1

James Hill
James Hill

Reputation: 61872

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.

Upvotes: 2

Related Questions