![](/img/trans.png)
[英]How do I Split string only at last occurrence of special character and use both sides after split
[英]Best way to split string by last occurrence of character?
假设我需要像这样拆分字符串:
输入字符串:“我的名字是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);
有人可以提出更优雅的方式吗?
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!"
}
你也可以使用一点LINQ。 第一部分有点冗长,但最后一部分非常简洁:
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!
string[] theSplit = inputString.Split('_'); // split at underscore
string firstPart = theSplit[0]; // get the first part
string secondPart = "_" + theSplit[1]; // get the second part and concatenate the underscore to at the front
编辑:以下评论; 这仅在输入字符串中有一个下划线字符实例时才有效。
更有趣......哎呀!
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; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.