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.
Related
I would like to remove the slash at the end of the URI, while keeping the query parameter.
For example:
I get an object of type URI as input with the value:
https://stackoverflow.com/questions/ask/
I would like to remove the last "/" to get:
https://stackoverflow.com/questions/ask
In some cases I may have parameters:
https://stackoverflow.com/questions/ask/?test=test1
I would like to get:
https://stackoverflow.com/questions/ask?test=test1
Thanks in advance.
string url1 = "https://stackoverflow.com/questions/ask/";
string url2 = "https://stackoverflow.com/questions/ask/?test=test1";
//remove slash at end
Console.WriteLine(url1.TrimEnd('/'));
//remove slash preceding query parameters
int last = url2.LastIndexOf('?');
url2 = url2.Remove(last - 1, 1);
Console.WriteLine(url2);
There probably is a way to search and replace the last slash using Regex as well, since there is Regex.Replace()
You can first check if the URL has any query parameters by checking latest index of ? character. If there is ?, take before that, remove last character (which is / that you don't want) and combine it again. If it doesn't have any query parameters, just remove the last character! You can create an extension method like this;
public static string RemoveSlash(this string url)
{
var queryIndex = url.LastIndexOf('?');
if (queryIndex >= 0)
{
var urlWithoutQueryParameters = url[..queryIndex];
if (urlWithoutQueryParameters.EndsWith("/"))
{
urlWithoutQueryParameters = urlWithoutQueryParameters[..^1];
}
var queryParemeters = url[queryIndex..];
return urlWithoutQueryParameters + queryParemeters;
}
else if (url.EndsWith("/"))
{
return url[..^1];
}
return url;
}
Then you can use it like this;
var url1 = "https://stackoverflow.com/questions/ask";
var url2 = "https://stackoverflow.com/questions/ask/";
Console.WriteLine(url1.RemoveSlash()); // https://stackoverflow.com/questions/ask
Console.WriteLine(url2.RemoveSlash()); // https://stackoverflow.com/questions/ask
var url3 = "https://stackoverflow.com/questions/ask/?test=test1";
var url4 = "https://stackoverflow.com/questions/ask?test=test1";
Console.WriteLine(url3.RemoveSlash()); // https://stackoverflow.com/questions/ask?test=test1
Console.WriteLine(url4.RemoveSlash()); // https://stackoverflow.com/questions/ask?test=test1
I have 3 possible input cases
string input = ""; // expected result: ""
string input = "bar-foo"; // expected result: "foo"
string input = "foo"; // expected result: "foo"
And I have to remove everyting including the first separator char - if exists.
Working approach:
string output = input.Split('-').LastOrDefault();
I want to solve this without Split() - my NOT working approach:
string output = input.Substring(input.IndexOf('-') );
How can I handle the IndexOutOfRangeException / make this code work?
Try to add 1:
string output = input.Substring(input.LastIndexOf('-') + 1);
If there's no - in the input, LastIndexOf returns -1 and so you'll have the entire string.
I've assumed that your are looking for input's suffix, that's why I've put LastIndexOf:
"123-456-789" -> "789"
If you want to cut off the prefix:
"123-456-789" -> "456-789"
please, change LastIndexOf into IndexOf
i think you should use Contains Method to identify - is available or not.
string a = "";
if (a.Contains("-"))
{
string output = input.Substring(input.LastIndexOf('-') + 1);
}
Why not just remove it from the string without checking:
input = input.Replace("-foo", string.Empty);
I need to insert some string value after the last slash. I have such string value:
string url = "http://blog.loc/blog/news/sport/slug1_slug2_slug3-slug";
I need to get this value:
"http://blog.loc/blog/news/sport/hot_slug1_slug2_slug3-slug"
So, I need to insert hot_ (for example), after the last slash. Could anyone help me?
I know you asked for regex, but it's not really necessary in my opinion.
You can just use string.Insert:
string url = "http://blog.loc/blog/news/sport/slug1_slug2_slug3-slug";
url = url.Insert(url.LastIndexOf("/") + 1, "hot_");
url now holds the value: http://blog.loc/blog/news/sport/hot_slug1_slug2_slug3-slug
Regex Method :
string url = "http://blog.loc/blog/news/sport/slug1_slug2_slug3-slug";
var matches = Regex.Matches(url, "/");
var match = matches[matches.Count - 1];
string result = url.Insert(match.Index + 1, "hot_")
In my code behind in C# I have the following code. How do I change the replace so that only
the first occurance of www is replaced?
For example if the User enters www.testwww.com then I should be saving it as testwww.com.
Currently as per the below code it saves as www.com (guess due to substr code).
Please help. Thanks in advance.
private string FilterUrl(string url)
{
string lowerCaseUrl = url.ToLower();
lowerCaseUrl = lowerCaseUrl.Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("ftp://", string.Empty);
lowerCaseUrl = lowerCaseUrl.Replace("www.", string.Empty);
string lCaseUrl = url.Substring(url.Length - lowerCaseUrl.Length, lowerCaseUrl.Length);
return lCaseUrl;
}
As Ally suggested. You are much better off using System.Uri. This also replaces the leading www as you wish.
private string FilterUrl(string url)
{
Uri uri = new UriBuilder(url).Uri; // defaults to http:// if missing
return Regex.Replace(uri.Host, "^www.", "") + uri.PathAndQuery;
}
Edit: The trailing slash is because of the PathAndQuery property. If there was no path you are left with the slash only. Just add another regex replace or string replace. Here's the regex way.
return Regex.Replace(uri.Host, "^www.", "") + Regex.Replace(uri.PathAndQuery, "/$", "");
I would suggest using indexOf(string) to find the first occurrence.
Edit: okay someone beat me to it ;)
You could use IndexOf like Felipe suggested OR do it the low tech way..
lowerCaseUrl = lowerCaseUrl.Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("ftp://", string.Empty).Replace("http://www.", string.Empty).Replace("https://www.", string.Empty)
Would be interested to know what you're trying to achieve.
Came up with a cool static method, also works for replacing the first x occurrences:
public static string ReplaceOnce(this string s, string replace, string with)
{
return s.ReplaceCount(replace, with);
}
public static string ReplaceCount(this string s, string replace, string with, int howManytimes = 1)
{
if (howManytimes < 0) throw InvalidOperationException("can not replace a string less than zero times");
int count = 0;
while (s.Contains(replace) && count < howManytimes)
{
int position = s.IndexOf(replace);
s = s.Remove(position, replace.Length);
s = s.Insert(position, with);
count++;
}
return s;
}
The ReplaceOnce isn't necessary, just a simplifier. Call it like this:
string url = "http://www.stackoverflow.com/questions/www/www";
var urlR1 - url.ReplaceOnce("www", "xxx");
// urlR1 = "http://xxx.stackoverflow.com/questions/www/www";
var urlR2 - url.ReplaceCount("www", "xxx", 2);
// urlR2 = "http://xxx.stackoverflow.com/questions/xxx/www";
NOTE: this is case-sensitive as it is written
The Replace method will change all content of the string. You have to locate the piece you want to remove using IndexOf method, and remove using Remove method of string. Try something like this:
//include the namespace
using System.Globalization;
private string FilterUrl(string url)
{
// ccreate a Comparer object.
CompareInfo myCompare = CultureInfo.InvariantCulture.CompareInfo;
// find the 'www.' on the url parameter ignoring the case.
int position = myCompare.IndexOf(url, "www.", CompareOptions.IgnoreCase);
// check if exists 'www.' on the string.
if (position > -1)
{
if (position > 0)
url = url.Remove(position - 1, 5);
else
url = url.Remove(position, 5);
}
//if you want to remove http://, https://, ftp://.. keep this line
url = url.Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("ftp://", string.Empty);
return url;
}
Edits
There was a part in your code that is removing a piece of string. If you just want to remove the 'www.' and 'http://', 'https://', 'ftp://', take a look the this code.
This code also ignore the case when it compares the url parameter and what you have been findind, on case, 'www.'.
I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: Remove All Text After Certain Point).
I've got the following code:
[Test]
public void stringManipulation()
{
String filename = "testpage.aspx";
String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);
String expected = "http://localhost:2000/somefolder/myrep/";
String actual = urlWithoutPageName;
Assert.AreEqual(expected, actual);
}
I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.
How can I get the remove the query string from the full URL such that this test passes?
For string manipulation, if you just want to kill everything after the ?, you can do this
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
input = input.Substring(0, index);
Edit: If everything after the last slash, do something like
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index); // or index + 1 to keep slash
Alternately, since you're working with a URL, you can do something with it like this code
System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Here's another simple solution. The following code will return everything before the '|' character:
if (path.Contains('|'))
path = path.Split('|')[0];
In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':
if (path.Contains('|'))
path = path.Split('|')[1];
(All I changed in the second piece of code was the index of the array.)
The Uri class is generally your best bet for manipulating Urls.
To remove everything before a specific char, use below.
string1 = string1.Substring(string1.IndexOf('$') + 1);
What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!
But for a URL, I would use the built in .NET class to take of that.
Request.QueryString helps you to get the parameters and values included within the URL
example
string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();
so the customername variable should be equal to dave
regards
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
you can use .NET's built in method to remove the QueryString.
i.e., Request.QueryString.Remove["whatever"];
here whatever in the [ ] is name of the querystring which you want to
remove.
Try this...
I hope this will help.
You can use this extension method to remove query parameters (everything after the ?) in a string
public static string RemoveQueryParameters(this string str)
{
int index = str.IndexOf("?");
return index >= 0 ? str.Substring(0, index) : str;
}