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

问题描述 投票:0回答:5

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

输入字符串:“我的名字是邦德_詹姆斯·邦德!” 输出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# string split
5个回答
182
投票

更新答案(适用于 C# 8 及以上版本)

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



15
投票

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!



8
投票
编辑:根据评论;仅当您的输入字符串中有一个下划线字符实例时,这才有效。


3
投票
假设您只想分割字符出现在第二个和更大的分割字符串上...
  1. 假设您想忽略重复的分割字符...
  2. 更多花括号...检查...
  3. 更优雅...也许...
  4. 更有趣...哎呀!!
  5. 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; });

    
        

0
投票

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]

    

© www.soinside.com 2019 - 2024. All rights reserved.