按字符的最后出现拆分字符串的最佳方法? [英] Best way to split string by last occurrence of character?

查看:51
本文介绍了按字符的最后出现拆分字符串的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要像这样分割字符串:

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

输入字符串:我的名字.是邦德._詹姆斯邦德!输出2个字符串:

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

  1. 我的名字.是邦德"
  2. "_詹姆斯·邦德!"

我尝试过:

int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal);
string firstPart = inputString.Remove(lastDotIndex);
string secondPart= inputString.Substring(lastDotIndex + 1, inputString.Length - firstPart.Length - 1);

有人可以提出更优雅的方式吗?

Can someone propose more elegant way?

推荐答案

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!"
}

这篇关于按字符的最后出现拆分字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆