c# - 按最后一次出现的字符拆分字符串的最佳方法?

标签 c# string split

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

输入字符串:“我的名字是 Bond._James Bond!” 输出 2 个字符串:

  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);

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

最佳答案

更新后的答案(针对 C# 8 及更高版本)

C# 8 引入了一个名为 ranges and indices 的新特性,它为处理字符串提供了更简洁的语法。

string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');

if (idx != -1)
{
    Console.WriteLine(s[..idx]); // "My. name. is Bond"
    Console.WriteLine(s[(idx + 1)..]); // "_James Bond!"
}

原始答案(适用于 C# 7 及以下版本)

这是使用 string.Substring(int, int) 方法的原始答案。如果您愿意,也可以使用此方法。

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

关于c# - 按最后一次出现的字符拆分字符串的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21733756/

相关文章:

c# - ASP.NET stripe.net 无法向没有事件卡的客户收费

c# - 在 .NET Core 的 Web 请求中使用 NTLM 身份验证

php - 正则表达式替换周围的字符,同时保留之间的字符串

c++ - 我的字符串不是从私有(private)变量复制的

Javascript 拆分不识别中间点

JavaScript String.split 在字符串文字上生成数组

c# - 电子表格齿轮和日期时间格式

c# - 从 .CS 代码文件中提取方法名称

php - 在 PHP 中,如何同时按空格、逗号和换行符拆分字符串

c# - 是否可以在 Java 或 C# 中实例化泛型类型的对象?