How to get the last word from string in C#

1 Answer

0 votes
using System;

class Program
{
    static void Main() {
        string s = "vb.net javascript php c c++ python c#";
        string lastWord = GetLastWord(s);
        Console.WriteLine("1. " + lastWord);
        
        lastWord = GetLastWord("");
        Console.WriteLine("2. " + lastWord);
 
        lastWord = GetLastWord("c#");
        Console.WriteLine("3. " + lastWord);
 
        lastWord = GetLastWord("c c++ java ");
        Console.WriteLine("4. " + lastWord);
 
        lastWord = GetLastWord("  ");
        Console.WriteLine("5. " + lastWord);
    }

    static string GetLastWord(string input) {
        if (string.IsNullOrWhiteSpace(input))
            return "";

        input = input.Trim(); // remove leading/trailing spaces

        int pos = input.LastIndexOf(" ");
        return pos > -1 ? input.Substring(pos + 1) : input;
    }
}


  
/*
run:
  
1. c#
2. 
3. c#
4. java
5. 
  
*/

 



answered Sep 8, 2019 by avibootz
edited Mar 27 by avibootz
...