Best way to split string by last occurrence of character?

前端 未结 4 846
情话喂你
情话喂你 2020-12-28 11:49

Let\'s say I need to split string like this:

Input string: \"My. name. is Bond._James Bond!\" Output 2 strings:

  1. \"My. name. is Bond\"
  2. \"_James
4条回答
  •  爱一瞬间的悲伤
    2020-12-28 12:26

    string s = "My. name. is Bond._James Bond!";
    int idx = s.LastIndexOf('.');
    
    if (idx != -1)
    {
        Console.WriteLine(s.Substring(0, idx)); // "My. name. is Bond"
        Console.WriteLine(s.Substring(idx + 1)); // "_James Bond!"
    }
    

提交回复
热议问题