How to trim the next line?

I have a string: "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get". I want to trim everything from the last slash, so I just stay with "Get".

+3
source share
6 answers

You can use the LastIndexOf method to get the position of the last / in the string and pass this to the Substring method as the number of characters you want to cut off from the string. This should leave you with 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 ) );
  }
+8
source
var s = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get";
s = s.Substring(s.LastIndexOf("/") + 1);
+9
source

URI, /Get/Put/Delete ..

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

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

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

Assert.AreEqual( "Get", s );

'/'.

.

+1

, ...

var s = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get";
if(s.ToLower().Contains("get"))   // or do some strict & case sensitive test  like /Get, /get as             
                                  //it will return true if your string contain /getawayfromme/
{
   s= "Get";                     // or whatever
}

The final result will be Get. In the above partitioning examples, it may fail if it occurs with more than one GET.

-1
source

All Articles