简体   繁体   中英

How do I trim the following string?

I have the string: "http://schemas.xmlsoap.org/ws/2004/09/transfer/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM