Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

string - C# equivalent to InStrRev

I have been searching for over an hour and I can not for the life of me figure out how to search a string variable starting on the right. What I want to do is to get the last folder of a path (right before the file name), In VB6 I would do something like this:

Dim s As String

s = "C:WindowsSystem32FooBar"

Debug.Print Mid(s, InStrRev(Left(s, Len(s) - 1), "") + 1)

Here is what I tried so far:

string s = "C:\WindowsSystem32\Foo\Bar";

s = agencyName.Substring(s.LastIndexOf("") + 1) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use strToSearch.LastIndexOf(strToFind);.

EDIT: I see you updated your question to say you've tried LastIndexOf(). This method works, I've used it many times.

You said you want to get the position where the filename starts. However, your example path contains no filename. (Since it ends with , that indicates it's a directory name.)

As suggested elsewhere, if you don't really want the last , then you need to specify the start index in order to tell LastIndexOf() to skip over the trailing backslashes you don't want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...