将所有字符都放在最后一个破折号的右边


114

我有以下内容:

string test = "9586-202-10072"

我如何使所有字符都位于最后一个字符的右边,-所以10072。字符数总是与最后一个破折号的右边不同。

如何才能做到这一点?

Answers:


235

你可以得到最后的位置-str.LastIndexOf('-')。因此,下一步很明显:

var result = str.Substring(str.LastIndexOf('-') + 1);

校正

就像Brian在下面指出的那样,在没有破折号的字符串上使用它会导致返回相同的字符串。


1
即使连字符是最后一个字符,此方法也有效,在这种情况下,它正确返回一个空字符串。仅当其中一个str为null或根本不包含连字符时,此操作才会失败。(在没有连字符的情况下,它不会抛出;它会返回整个源字符串。)
LukeH 2011年

@LukeH:感谢您的注意。我没有检查,并错误地认为它会抛出。
乔恩

3
好吧,LastIndexOf如果什么都没找到,则返回-1(这是记录的行为,因此可以放心地依靠它)。 str.Substring(1-1)给您一个等于的字符串str。毫不奇怪,这里。
布莱恩(Brian)

2
@Brian:我想我在同一个琐碎的陈述中打破了大多数错误的记录。教训:写完事实后,请不要对代码进行任何校对。谢谢。
乔恩

57

您可以使用LINQ,并保存自己的显式解析:

string test = "9586-202-10072";
string lastFragment = test.Split('-').Last();

Console.WriteLine(lastFragment);

5
这可能会节省最多的开发人员时间,但是在一般情况下,请注意,像这样的代码将分配许多字符串分配(在上面的示例中可能为四个),因此在性能关键的部分中可能会不加强调。
查尔斯·伯恩斯

5
string tail = test.Substring(test.LastIndexOf('-') + 1);

4
YourString.Substring(YourString.LastIndexOf("-"));

4
如果在末尾排除“ +1”,则输出将包含特殊字符以及字符串。
米纳

3

我可以看到该帖子被浏览了46,000次。我敢打赌,在这46,000名观众中,有许多人只是因为他们只想要文件名而问这个问题...如果您不能使用at符号使子字符串逐字逐句地出现,那么这些答案可能是个难题。

如果您只是想获取文件名,那么这里有一个简单的答案。即使这不是问题的确切答案。

result = Path.GetFileName(fileName);

参见https://msdn.microsoft.com/zh-cn/library/system.io.path.getfilename(v=vs.110).aspx




1
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");

if (indexOfHyphen >= 0)
{
    string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
    Console.WriteLine(contentAfterLastHyphen );
}

0

我为此创建了一个字符串扩展名,希望对您有所帮助。

public static string GetStringAfterChar(this string value, char substring)
    {
        if (!string.IsNullOrWhiteSpace(value))
        {
            var index = value.LastIndexOf(substring);
            return index > 0 ? value.Substring(index + 1) : value;
        }

        return string.Empty;
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.