假设我需要像这样分割字符串:
输入字符串:“我的名字是邦德_詹姆斯·邦德!” 输出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 引入了一项名为“范围和索引”的新功能,它为处理字符串提供了更简洁的语法。
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!"
}
string input = "My. name. is Bond._James Bond!";
string[] split = input.Split('.');
string firstPart = string.Join(".", split.Take(split.Length - 1)); //My. name. is Bond
string lastPart = split.Last(); //_James Bond!
编辑:根据评论;仅当您的输入字符串中有一个下划线字符实例时,这才有效。
var s = "My. name. is Bond._James Bond!";
var firstSplit = true;
var splitChar = '_';
var splitStrings = s.Split(new[] { splitChar }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
if (!firstSplit)
{
return splitChar + x;
}
firstSplit = false;
return x;
});
var s = "My. name. is Bond._James Bond!";
var idx = s.LastIndexOf(".");
if (s.Split(".") is [.. var first, var last])
{
Console.WriteLine(string.Join(".", first));
Console.WriteLine(last);
}
明显的缺点是第一部分具有相同字符的拆分和连接。如果您只对最后一部分感兴趣,那么您可以使用
is [.., var last]
。