2014-02-12 39 views
24

假设我需要像这样拆分字符串:通过最后一次出现的字符拆分字符串的最佳方法是什么?

输入字符串:“我的名字是Bond._James Bond!” 输出2串:

  1. “我的名字是邦德”
  2. “!_James邦德”

我尝试这样做:

​​

有人能提出更优雅的方式?

+0

我会说,底线是完全有你拆就。如果你真的需要输出的第二部分,可以在该符号上进行拆分,并可能再次手动添加它。 –

+0

不清楚你想如何处理下划线。它总是存在?应该从输出中删除,你需要保留它吗? – Steve

回答

69
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!" 
} 
+1

奖励 - 如果idx == -1即不爆炸,没有'''' –

+0

@CADbloke咦?我相信它的确如此! –

+0

如果找不到“。”然后idx == -1,你添加一个(最后一行),这是零,字符串的开始(https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx )。如果没有“。”,它将返回整个字符串。 –

8
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 

编辑:从评论以下;这只适用于输入字符串中有下划线字符的一个实例。

+7

值得注意---只有当字符串出现单个字母时,这才能正常工作。在这个例子中这是真实的,当OP在实际实践中使用它时可能不是这样。 –

+0

@drew_w你说得对。 – rex

+0

只需要提供'string [] theSplit = inputString.Split(new char [] {'_'},2);' –

7

您还可以使用一点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! 
2
  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; 
        }); 
    
相关问题