简体   繁体   中英

Split and get last part of a string in c#

I have string like "abc-def-gef". I need to remove the first part of the string from "-" and get the last part like "def-gef". How its possible in c#. Please help me to find out the solution.

Thank you.

This is a simple way I would do it if you always want the last one and the delimeter is always '-'.

var myString =  "abc-def-gef";

var result = myString.Split('-').Last();

Output: "gef"

var result2 = myString.Split('-').Skip(1).Take(2);

Output : An IEnumerable of "gef" "def"

here:

string str = "abc-def-gef";
str = str.Substring(str.IndexOf("-")+1);

IndexOf("-") will return the index of the first "-" and Substring will cut the string from that index (+1 to skip "-") to the end of the string

As Alex said, you can use Substring in combination with LastIndexOf

    var str = "abc-def-gef";
    var newStr = str.Substring(str.LastIndexOf("-") + 1); //returns gef

or

    var str = "abc-def-gef";
    var newStr = str.Substring(str.IndexOf("-") + 1); //returns def-gef

something like this. Please correct syntax for the same:

string inpt = "abc-def-gef";
string[] arr = inp.Split('-');
string result = arr[1] + "-" +arr[2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM