开发者

How to split string using Substring

I have a string like '/Test1/Test2', and i need to take Test2 separated f开发者_如何学运维rom the same. How can i do that in c# ?


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


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.


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


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


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

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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜