最后一次出现字符时分割字符串的最佳方法?

use*_*838 46 c# string split

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

输入字符串:"我的名字是Bond._James Bond!" 输出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);
Run Code Online (Sandbox Code Playgroud)

有人可以提出更优雅的方式吗?

Phi*_*l K 112

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!"
}
Run Code Online (Sandbox Code Playgroud)

  • 额外的好处 - 如果 `idx == -1` 则不会爆炸,即没有 `'.'` (2认同)
  • 是的,但是当`idx = -1`时`s.Substring(0,idx)`会抛出异常。我将编辑答案以包含一个`if`语句以使这一点变得清楚。 (2认同)

Pie*_*ult 14

你也可以使用一点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!
Run Code Online (Sandbox Code Playgroud)


rex*_*rex 9

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
Run Code Online (Sandbox Code Playgroud)

编辑:以下评论; 这仅在输入字符串中有一个下划线字符实例时才有效.

  • 值得注意的是---只有当字符串出现一次字母时才能正常工作.在这个例子中这是正确的,当OP在实际操作中使用它时可能不是这样. (7认同)