MaXi32
MaXi32

Reputation: 668

How to get the second last string in C#

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

Answers (4)

j03z
j03z

Reputation: 171

string input = "Village Siaban  WDT no.39 91308 Semporna Sabah";

string secondToLastWord = input.Split(' ').Reverse().ElementAt(1).ToString();

Upvotes: 2

user287107
user287107

Reputation: 9417

why not using a regex?

   var word = Regex.Match(input, ".* ([^ ]*) [^ ]*").Groups[1];

Upvotes: 1

Just for fun:

string input = "Village Siaban  WDT no.39 91308 Semporna Sabah";
input.Split(' ').Reverse().Take(2).Last();

Upvotes: 3

Sudhakar Tillapudi
Sudhakar Tillapudi

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

Related Questions