Answers:
你可以得到最后的位置-用str.LastIndexOf('-')。因此,下一步很明显:
var result = str.Substring(str.LastIndexOf('-') + 1);
校正:
就像Brian在下面指出的那样,在没有破折号的字符串上使用它会导致返回相同的字符串。
LastIndexOf如果什么都没找到,则返回-1(这是记录的行为,因此可以放心地依靠它)。 str.Substring(1-1)给您一个等于的字符串str。毫不奇怪,这里。
我可以看到该帖子被浏览了46,000次。我敢打赌,在这46,000名观众中,有许多人只是因为他们只想要文件名而问这个问题...如果您不能使用at符号使子字符串逐字逐句地出现,那么这些答案可能是个难题。
如果您只是想获取文件名,那么这里有一个简单的答案。即使这不是问题的确切答案。
result = Path.GetFileName(fileName);
参见https://msdn.microsoft.com/zh-cn/library/system.io.path.getfilename(v=vs.110).aspx
请参见String.lastIndexOf方法
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");
if (indexOfHyphen >= 0)
{
string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
Console.WriteLine(contentAfterLastHyphen );
}
str为null或根本不包含连字符时,此操作才会失败。(在没有连字符的情况下,它不会抛出;它会返回整个源字符串。)