假设我需要像这样分割字符串:
输入字符串:“我的.名称.是Bond._James键!”输出2个字符串:
我试过这个:
int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal);
string firstPart = inputString.Remove(lastDotIndex);
string secondPart= inputString.Substring(lastDotIndex + 1, inputString.Length - firstPart.Length - 1);有人能提出更优雅的方式吗?
发布于 2014-02-12 16:37:24
更新的答案(适用于C# 8及以上)
C# 8引入了一个名为范围和指数的新特性,它为处理字符串提供了更简洁的语法。
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!"
}发布于 2014-02-12 16:42:38
您也可以使用一点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!发布于 2014-02-12 16:31:52
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编辑:以下是注释;只有在输入字符串中有一个下划线字符的实例时,才能这样做。
https://stackoverflow.com/questions/21733756
复制相似问题