首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用上次出现的字符来分割字符串的最佳方法?

用上次出现的字符来分割字符串的最佳方法?
EN

Stack Overflow用户
提问于 2014-02-12 16:29:32
回答 4查看 91.3K关注 0票数 77

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

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

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

我试过这个:

代码语言:javascript
复制
int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal);
string firstPart = inputString.Remove(lastDotIndex);
string secondPart= inputString.Substring(lastDotIndex + 1, inputString.Length - firstPart.Length - 1);

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-02-12 16:37:24

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

C# 8引入了一个名为范围和指数的新特性,它为处理字符串提供了更简洁的语法。

代码语言:javascript
复制
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)方法的原始答案。如果你愿意的话,使用这种方法还是可以的。

代码语言:javascript
复制
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!"
}
票数 172
EN

Stack Overflow用户

发布于 2014-02-12 16:42:38

您也可以使用一点LINQ。第一部分有点冗长,但最后一部分相当简洁:

代码语言:javascript
复制
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!
票数 15
EN

Stack Overflow用户

发布于 2014-02-12 16:31:52

代码语言:javascript
复制
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

编辑:以下是注释;只有在输入字符串中有一个下划线字符的实例时,才能这样做。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21733756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档