Extract the last word from a string using C#

前端 未结 7 1767
醉梦人生
醉梦人生 2020-12-15 16:37

My string is like this:

string input = \"STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API\";

Here actually I want to extract the last word, \'API\', an

7条回答
  •  没有蜡笔的小新
    2020-12-15 17:14

    static class Extensions
    {
        private static readonly char[] DefaultDelimeters = new char[]{' ', '.'};
    
        public string LastWord(this string StringValue)
        {
            return LastWord(StringValue, DefaultDelimeters);
        }
    
        public string LastWord(this string StringValue, char[] Delimeters)
        {
            int index = StringValue.LastIndexOfAny(Delimeters);
    
            if(index>-1)
                return StringValue.Substring(index);
            else
                return null;
        }
    }
    
    class Application
    {
        public void DoWork()
        {
            string sentence = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
            string lastWord = sentence.LastWord();
        }
    }
    

提交回复
热议问题