假设我需要像这样拆分字符串:通过最后一次出现的字符拆分字符串的最佳方法是什么?
输入字符串:“我的名字是Bond._James Bond!” 输出2串:
- “我的名字是邦德”
- “!_James邦德”
我尝试这样做:
有人能提出更优雅的方式?
假设我需要像这样拆分字符串:通过最后一次出现的字符拆分字符串的最佳方法是什么?
输入字符串:“我的名字是Bond._James Bond!” 输出2串:
我尝试这样做:
有人能提出更优雅的方式?
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!"
}
奖励 - 如果idx == -1即不爆炸,没有'''' –
@CADbloke咦?我相信它的确如此! –
如果找不到“。”然后idx == -1,你添加一个(最后一行),这是零,字符串的开始(https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx )。如果没有“。”,它将返回整个字符串。 –
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
编辑:从评论以下;这只适用于输入字符串中有下划线字符的一个实例。
值得注意---只有当字符串出现单个字母时,这才能正常工作。在这个例子中这是真实的,当OP在实际实践中使用它时可能不是这样。 –
@drew_w你说得对。 – rex
只需要提供'string [] theSplit = inputString.Split(new char [] {'_'},2);' –
您还可以使用一点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!
更多乐趣......哎呀呀!
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;
});
我会说,底线是完全有你拆就。如果你真的需要输出的第二部分,可以在该符号上进行拆分,并可能再次手动添加它。 –
不清楚你想如何处理下划线。它总是存在?应该从输出中删除,你需要保留它吗? – Steve