Reputation: 574
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.
Upvotes: 2
Views: 21226
Reputation: 186
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"
Upvotes: 14
Reputation: 221
something like this. Please correct syntax for the same:
string inpt = "abc-def-gef";
string[] arr = inp.Split('-');
string result = arr[1] + "-" +arr[2];
Upvotes: -1
Reputation: 2950
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
Upvotes: 3
Reputation: 1480
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
Upvotes: 5