【问题标题】:Best way to split string by last occurrence of character?按最后一次出现的字符拆分字符串的最佳方法?
【发布时间】:2014-02-12 16:29:32
【问题描述】:

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

输入字符串:“我的名字。是邦德。_詹姆斯邦德!” 输出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


【解决方案1】:

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

C# 8 引入了一个名为 ranges and indices 的新功能,它为处理字符串提供了更简洁的语法。

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

【讨论】:

  • 红利 - 如果idx == -1 不会爆炸,即没有'.'
  • @CADbloke 嗯?我相信是的!
  • 如果没有找到“.”然后 idx == -1,添加一个(最后一行),即零,字符串的开头(msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx)。如果没有“.”,它将返回整个字符串。
  • 是的,但是当idx = -1s.Substring(0, idx) 会抛出异常。我将编辑答案以包含 if 声明以明确这一点。
【解决方案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!

【讨论】:

    【解决方案3】:
    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
    

    编辑:来自 cmets;这仅在您的输入字符串中有一个下划线字符实例时才有效。

    【讨论】:

    • 值得注意 --- 这只有在字符串中出现单个字母时才能正常工作。这在示例中是正确的,当 OP 在实际实践中使用它时可能不是正确的。
    • 只提供像string[] theSplit = inputString.Split(new char[] { '_' }, 2);这样的分割数
    【解决方案4】:
    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;
          });
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-21
      • 2014-01-12
      • 2017-02-23
      • 2021-12-02
      • 2017-04-29
      • 2022-01-25
      • 2019-01-06
      • 2015-01-18
      相关资源
      最近更新 更多