How to get the second last string in C#

后端 未结 4 1643
梦谈多话
梦谈多话 2021-01-22 01:45

Example1:

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

Example2:

string input = \"Village Hw WDT no.39          


        
相关标签:
4条回答
  • string input = "Village Siaban  WDT no.39 91308 Semporna Sabah";
    
    string secondToLastWord = input.Split(' ').Reverse().ElementAt(1).ToString();
    
    0 讨论(0)
  • 2021-01-22 02:23

    why not using a regex?

       var word = Regex.Match(input, ".* ([^ ]*) [^ ]*").Groups[1];
    
    0 讨论(0)
  • 2021-01-22 02:26

    Just for fun:

    string input = "Village Siaban  WDT no.39 91308 Semporna Sabah";
    input.Split(' ').Reverse().Take(2).Last();
    
    0 讨论(0)
  • 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];
    
    0 讨论(0)
提交回复
热议问题