开发者

How do I trim the following string?

I have the string: "http://schemas.xmlsoap.org/ws/2004/09/tr开发者_运维知识库ansfer/Get". I want to trim everything from the last slash, so I just remain with "Get".


var s = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get";
s = s.Substring(s.LastIndexOf("/") + 1);


You could use the LastIndexOf method to get the position of the last / in the string and pass that into the Substring method as how many characters you want to trim off the string. That should leave you with the Get at the end.

[TestMethod]
  public void ShouldResultInGet()
  {
     string url = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get";

     int indexOfLastSlash = url.LastIndexOf( '/' ) + 1; //don't want to include the last /

     Assert.AreEqual( "Get", url.Substring( indexOfLastSlash ) );
  }


Use String.LastIndexOf to get the last forward slash

http://msdn.microsoft.com/en-us/library/ms224422.aspx


URI alternative if your using the well formed /Get /Put /Delete etc

var uri = new System.Uri("http://schemas.xmlsoap.org/ws/2004/09/transfer/Get");
string top = Path.GetFileName(uri.LocalPath);


try

int indexOfLastSlash = url.LastIndexOf( '/' ) + 1;

string s = url.Remove(0, indexOfLastSlash);

Assert.AreEqual( "Get", s );

this removes all data before & including the last '/'.

works fine here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜