假设我需要像这样拆分字符串:
输入字符串:“我的名字是 Bond._James Bond!” 输出 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/