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

时间:2014-02-12 16:29:33

标签: c# string split

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

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

  1. “我的名字就是邦德”
  2. “_詹姆斯邦德!”
  3. 我试过了:

    int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal);
    string firstPart = inputString.Remove(lastDotIndex);
    string secondPart= inputString.Substring(lastDotIndex + 1, inputString.Length - firstPart.Length - 1);
    

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

4 个答案:

答案 0 :(得分:103)

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 :(得分:12)

你也可以使用一点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 :(得分: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

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

答案 3 :(得分: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;
        });
    
相关问题