C# substring after specific sign - c#

how can I get a value of the string after last'/'
string path=http://localhost:26952/Images/Users/John.jpg
I would like to have as a result something like :
John.jpg

I think using Path.GetFileName method is a better way instead of string manipulation.
string path = "http://localhost:26952/Images/Users/John.jpg";
var result = Path.GetFileName(path);
Console.WriteLine(result); // John.jpg

Split by '/' and get the last part:
var url = "http://localhost:26952/Images/Users/John.jpg";
var imageName = url.Split('/').Last();

Related

Remove remaining url after htm?

i need to remove the url path starting from /deposit/jingdongpay.htm?bid=4089
'?' i just need /deposit/jingdongpay.htm.
It means that the url will remove anything that comes after .htm
Any idea how to do it.
In Python, you can use str.split():
url = "/deposit/jingdongpay.htm?bid=4089"
split_url = url.split('?')
>>> split_url
['/deposit/jingdongpay.htm', 'bid=4089']
>>> split_url[0]
'/deposit/jingdongpay.htm'
You can use the String.Split method:
string url = "/deposit/jingdongpay.htm?bid=4089";
string result = url.Split('?')[0];
Another approach would be to use String.Substring:
string result = url.Substring(0, url.IndexOf('?'));
Or maybe if you are interested in a LINQ solution:
string result = new string(url.TakeWhile(c => c != '?').ToArray());
result = "/deposit/jingdongpay.htm"

How to trim string started from substring

How to remove in elegance way second part of string starting from particular substring?
Ex.
We have string:
var someString = "ThisIsSomeString_v1_26102017";
as a result we want: ThisIsSomeString
I did that:
var someString = "ThisIsSomeString_v1_26102017";
var tokens = someString.SplitByLast("_v");
var result = tokens[0];
There is any clever way to do that? Some Trim or something?
I mean as a result I want to have first part of string. In this case separator is a "_v" substring. I want to drop everything after "_v" included this "_v".
Use string.Substring:
var result = someString.Substring(0, Math.Max(someString.IndexOf("_v"), 0));
Not any better than the Substring implementation, the Split might look like this:
var result = someString.Split(new[]{"_v"}, StringSplitOptions.None).First();
Do like this -
var result = str.Substring(0, str.LastIndexOf("_v"));
It will remove all the text after _v (including _v).
What's wrong with:
var result = input?.Split(new[] { "_v" }, StringSplitOptions.None)[0];

How to split a defined string from another string and get the first item after split

I have this string D:\ASN\Documents\ENU\LO\ANL\File\05003ede-59bf-45c6-bb57-a6111e9f18e0\linux-cheat-sheet.pdf and I want to exclude this string D:\ASN\Documents\ENU\LO from the above string and then get the first string(in this case ANL)after the split.
I tried something like this:
string fullpath = "D:\\ASN\\Documents\\ENU\\LO\\ANL\\File\\05003ede-59bf-45c6-bb57-a6111e9f18e0\\linux-cheat-sheet.pdf"
string[] sep = new string[]{"D:\\ASN\\Documents\\ENU\\LO"};
string [] result = fullpath.split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write(s.Substring(s.IndexOf(#"\") + 1));
}
But this is giving me ANL\File\05003ede-59bf-45c6-bb57-a6111e9f18e0\linux-cheat-sheet.pdf". Instead I need only ANL. How can this be achieved? Is there any other way to get this instead of this way.
TIA
var result = fullpath.Replace(samplePath, "").Split('\\')[1];
You can replace the first part (samplePath) with nothing, removing it (or you could use Substring to get the second part of the fullPath, counting the characters of samplePath), and then Split the result on '\', getting the second occurrence, which is the result you expect.
Here's a working version: https://dotnetfiddle.net/k4tfGP
Can you do a split on the second string when it sees the \?
String sampleString = "ANL\File\05003ede-59bf-45c6-bb57-a6111e9f18e0\linux-cheat-sheet.pdf"";
String[] stringArray = sampleString.split("\");
String wantedString = stringArray[0];
This is not what split() is intended for. split() is generally used to divide your string into multiple sections based on a separator. In your case, you might have wanted to use it to separate the sub-folders by splitting on '\'.
But you want something else -- to remove a section of text. If you know that the text will always be at the start, try this:
string result = fullpath.Substring("D:\\ASN\\Documents\\ENU\\LO".Length);
This will return the original string, minus the first X characters, where X is exactly the length of the string you want to remove.
string fullpath =
"D:\\ASN\\Documents\\ENU\\LO\\ANL\\File\\05003ede-59bf-45c6-bb57-a6111e9f18e0\\linux-cheat-sheet.pdf";
string[] sep = new string[] {"D:\\ASN\\Documents\\ENU\\LO"};
string[] result = fullpath.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write(s.Substring(s.IndexOf(#"\") + 1, s.IndexOf(#"\", 2) - 1));
}
String.IndexOf will get you the index of the first, but has overloads giving a starting point. So In this example, I have given the starting point as "2" as your path contains "\\" always.
string basepath = "D:\\ASN\\Documents\\ENU\\LO\\";
string fullpath = "D:\\ASN\\Documents\\ENU\\LO\\ANL\\File\\05003ede-59bf-45c6-bb57-a6111e9f18e0\\linux-cheat-sheet.pdf";
fullpath = fullpath.Replace(basepath, "");
string returnValue = fullpath.Remove(fullpath.IndexOf("\\"), fullpath.Length-fullpath.IndexOf("\\"));
Worked here...

Add a directory name to a URL address using C#

I have a textbox where users can paste a URL address. I want to add a directory name to the URL before saving it in the database.
<asp:TextBox ID="urlTextbox" runat="server"></asp:TextBox>
Code behind
TextBox url = urlTextbox as TextBox;
string urlString = urlTextbox.Text;
Let's say the urlString = "mydomain.com/123456". I want to replace it with "mydomain.com/directory/123456". mydomain.com/directory is the same for all the URLs. The last part "123456" changes only.
Thank you
I'd suggest seeing if your needs are met with the UriBuilder class.
UriBuilder url = new UriBuilder(urlTextbox.Text);
Now you can use the various properties to change your url.
string formattedUrl = string.Format("{0}://{1}/directory/{2}", url.Scheme, url.Host, url.Path);
A better idea is to adjust the URL with another / same UriBuilder as noted by Jared.
UriBuilder url = new UriBuilder(urlTextbox.Text);
url.Path = string.Format("directory/{0}", url.Path);
Use this object as a Uri by simply doing this
Uri formattedUrl = url.Uri;
Or convert to a string if needed.
string formattedUrl = url.ToString();
You can also use Uri.TryParse(...) to verify if it's a valid URL being entered into the text box.
To get the individual query parameters, you can look at the Uri object.
UriBuilder url = new UriBuilder("mydomain.com/123456?qs=aaa&bg=bbb&pg=ccc");
url.Path = string.Format("directory/{0}", url.Path);
Uri formattedUrl = url.Uri;
string queryString = formattedUrl.Query;
// parse the query into a dictionary
var parameters = HttpUtility.ParseQueryString(queryString);
// get your parameters
string qs = parameters.Get("qs");
string bg = parameters.Get("bg");
string pg = parameters.Get("pg");
You can use string functions Split and Join to achieve your result. An example code is shown below
List<string> parts = urlString.Split(new char[] { '/'}).ToList();
parts.Insert(parts.Count - 1, "directory");
urlString = string.Join("/", parts);
This is one way of doing. Split the urlString using .split() function.
string[] parts = urlString.Split('/');
parts[parts.Length-1] will have that number. Append it to the string you want.
I'd do something like this:
//Assuming the address in urlString has the format mydomain.com/123456
string[] urlParts = urlString.Split('/');
string directory = "directory";
string finalUrl = urlParts[0] + "/" + directory + "/" + urlParts[1];
Be careful if the address has other "/" characters, like if preceded by http:// or something like that.
Hope it helps.
Simply use concatenation:
save in a temporary string
temp="mydomain.com/directory/"
and save the changing part in another string like
temp2="123456"
now concatenate both temp1 and temp2 like below.
urlString=temp1+temp2;

How to split the two strings using filetype.split?

I have got a string as follows:
string name ="C:\folder\back-201190082233.zip";
How can I get only the part 201190082233 from the string name? I have tried like this for getting the only the part 201190082233
string filetype = name;
string[] getfiledate = filetype.Split('-');
But I am getting the part 201190082233.zip. Now I want to get only the part 201190082233. Would anyone please help on this?
Seems like a good idea to use regular expressions:
var match = Regex.Match("back.201190082233.zip" , #"(?<=-)\d+(?=\.)");
if(match.Success)
{
var numericPart = match.Value;
}
Edit:
If you're dealing with paths, .Net offers help:
string name = #"C:\folder\back.201190082233.zip";
var fileName = Path.GetFileName(name);
var match = Regex.Match(fileName , #"(?<=-)\d+(?=\.)");
if(match.Success)
{
var numericPart = match.Value;
}
string name = "C:\folder\back-201190082233.zip";
string filetype = name;
string[] getfiledate = filetype.Split(new[] {'.', '-'});
string datepart = getfiledate[1];
How about this way?
var fileDate= filetype.Split('.')[1];
Edit for updates
var fileDate = Path.GetFileNameWithoutExtension(filetype).Split('.')[0]
Probably
var date = Path.GetFileNameWithoutExtension( name ).Split('-')[1];
would be sufficient.
See documentation for function Path.GetFileNameWithoutExtension.
Why are you splitting with a '-' ? Shouldn't it be '.' ?
string numberPart = filetype.Split('.')[1];
You may use something like below
string str = name.Split(".")[1];
Hope this helps!!
or if the string changes you could use a mor specific regular expression like this:
string s = Regex.Replace("back.201190082233.zip", #"[^\.]+\.([^\.]+)\..*", "$1");

Categories