Reputation: 668
Example1:
string input = "Village Siaban WDT no.39 91308 Semporna Sabah";
Example2:
string input = "Village Hw WDT no.39 91308 Sandakan Sarawak";
How do I extract the second last words and print it out. For this case from the Example1 is Semporna and Example2 is Sandakan.
Upvotes: 2
Views: 6104
Reputation: 171
string input = "Village Siaban WDT no.39 91308 Semporna Sabah";
string secondToLastWord = input.Split(' ').Reverse().ElementAt(1).ToString();
Upvotes: 2
Reputation: 9417
why not using a regex?
var word = Regex.Match(input, ".* ([^ ]*) [^ ]*").Groups[1];
Upvotes: 1
Reputation: 2520
Just for fun:
string input = "Village Siaban WDT no.39 91308 Semporna Sabah";
input.Split(' ').Reverse().Take(2).Last();
Upvotes: 3
Reputation: 26209
Step 1: You can Split
the String using space
delimeter to get all words from String.
Step 2: You can use the WordsLength-2
to get the 2'nd word from Last.
Try This:
string input = "Village Siaban WDT no.39 91308 Semporna Sabah";
var words = input.Split(' ');
var reqWord = "";
if(words.Length > 1)
reqWord = words[words.Length-2];
Upvotes: 4