I have some Urls string, such as:
http://www.testproject.com/tokyo/4
http://www.testproject.com/india/11
http://www.testproject.com/singapore/819
How to get the number ("4". "11", "819") in the end of Url?
The other answers using string methods would be correct if this was a simple string, but since this is a URL, you should use the proper class to handle URIs:
var url = new Uri("http://www.testproject.com/tokyo/4");
var lastSegment = url.Segments.Last();
Without using regex, you can find the index of last "/" by using string.LastIndexOf('/') and get the rest by using string.SubString
Example of what AD.Net meant:
public string getLastBit(string s) {
int pos = s.LastIndexOf('/') + 1;
return s.Substring(pos, s.Length - pos);
}
Returns:
4, 11, 819
When passed in an individual url.
string myUrl = "http://www.testproject.com/tokyo/4";
string[] parts = myUrl.Split('/');
string itIsFour = parts[parts.Length-1];
int LastFwdSlash = URLString.LastIndexOf('/');
String Number = URLString.Substring(LastFwdSlash + 1, URLString.Length);
int Number = int.Parse(URLString);
Related
I have a string: [(10.3.4.5:83/001_3CX/asd_43)]
From this string I want to get two strings:
10.3.4.5:83
001_3CX/asd_43
What is the best solution for this?
I'm coding in c#.
RegEx appraoch https://dotnetfiddle.net/7ZJhUL
string input = "[(10.3.4.5:83/001_3CX/asd_43)]";
Match result = Regex.Match(input, #"\[\((.*?)\/(.*)\)\]");
string first = result.Groups[1].Value; //10.3.4.5:83
string second = result.Groups[2].Value; //001_3CX/asd_43
string test = "[(10.3.4.5:83/001_3CX/asd_43)]";
test.replace_string_by_character("[(","");
test.replace_string_by_character(")]","");
// (current result) test = "10.3.4.5:83/001_3CX/asd_43"
int index = locate_character_inside_string("/",test);
string first_to_return = substring_basedon_index(test,0,index - 1);
string second_to_return = substring_basedon_index(test,index + 1, length(test));
// (result) first_to_return = "10.3.4.5:83";
// (result) second_to_return = "001_3CX/asd_43";
There are plenty of internet posts on the exact names of the functions and methods I've mentioned :-)
I want to get the page name from a URI for instance if I have
"/Pages/Alarm/AlarmClockPage.xaml"
I want to get AlarmClockPage
I tried
//usage GetSubstring("/", ".", "/Pages/Alarm/AlarmClockPage.xaml")
public static string GetSubstring(string a, string b, string c)
{
string str = c.Substring((c.IndexOf(a) + a.Length),
(c.IndexOf(b) - c.IndexOf(a) - a.Length));
return str;
}
But because the string being search may contain one or more forward slashes, I don't think this method work in such case.
So how do I consider the multiple forward slashes that may present?
Why don't you use method which is already in the framework?
System.IO.Path.GetFileNameWithoutExtension(#"/Pages/Alarm/AlarmClockPage.xaml");
If you only want to use string functions, you may try:
var startIdx = pathString.LastIndexOf(#"/");
var endIdx = pathString.LastIndexOf(".");
if(endIdx!=-1)
{
fileName = pathString.Substring(startIdx,endIdx);
}
else
{
fileName = pathString.Substring(startIdx);
}
It gives file name from a given file path. try this
string pageName = System.IO.Path.GetFileName(#"/Pages/Alarm/AlarmClockPage.xaml");
I am making an application which "Filewatches" a folder and when a file is created in there it will automatically be mailed to the customer.
The problem is that i haven't found any information on how to split filenames
For example i have a file called : "Q1040500005.xls"
I need the first 5 characters seperated from the last 5, so basically split it in half (without the extension ofcourse)
And my application has to recognize the "Q1040" and the "500005" as seperate strings.
Which will be recognized in the database which contains The query number (Q1040) and the customer number "500005" the email of the customer and the subject of the queryfile.
How can i do this the easiest way?
Thanks for the help!
Use SubString method http://msdn.microsoft.com/es-es/library/aka44szs(v=vs.80).aspx
int lengthFilename = filename.Length - 4; //substract the string ".xls";
int middleLength = lengthFilename/2;
String filenameA = filename.SubString(0, middleLength);
String filenameB = filename.SubString(middleLength, lengthFilename - middleLength);
Is string.Substring method what you're looking for?
Use String.SubString(int startindex, int length)
String filename = Q1040500005.xls
var queryNumber = filename.Substring(0, 5); //Q1040
var customerNumber = filename.Substring(5, 6); //500005
This assumes your strings are a constant length.
Hope this helps.
You can use string.SubString() here
string a = fileName.SubString(0, 5); // "Q1040"
string b = fileName.SubString(5, 5); // "50000" <- Are you sure you didn't mean "last 6"?
string b2 = fileName.SubString(5, 6); // "500005"
This only works, if both strings have a constant fixed length
Edit:
If on the other hand, both strings can have variable length, I'd recommend you use a separator to divide them ("Q1040-500005.xml"), then use string.Split()
string[] separatedStrings = fileName.Split(new char[] { '-', '.' });
string a = separated[0]; // "Q1040"
string b = separated[1]; // "500005"
string extension = separated[2]; // "xls"
I have a string that looks like
string url = "www.example.com/aaa/bbb.jpg";
"www.example.com/" is 18 fixed in length. I want to get the "aaa/bbb" part from this string (The actual url is not example nor aaa/bbb though, the length may vary)
so here's what I did:
string newString = url.Substring(18, url.Length - 4);
Then I got the exception: index and length must refer to a location within the string. What's wrong with my code and how to fix it?
The second parameter in Substring is the length of the substring, not the end index (in other words, it's not the length of the full string).
You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.
Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:
var prefix = "www.example.com/";
var suffix = ".jpg";
string url = "www.example.com/aaa/bbb.jpg";
if (url.StartsWith(prefix) && url.EndsWith(suffix) && url.Length >= (prefix.Length + suffix.Length))
{
string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length);
Console.WriteLine(newString);
}
else
//handle invalid state
Your mistake is the parameters to Substring. The first parameter should be the start index and the second should be the length or offset from the startindex.
string newString = url.Substring(18, 7);
If the length of the substring can vary you need to calculate the length.
Something in the direction of (url.Length - 18) - 4 (or url.Length - 22)
In the end it will look something like this
string newString = url.Substring(18, url.Length - 22);
How about something like this :
string url = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(url);
string path_Query = uri.PathAndQuery;
string extension = Path.GetExtension(path_Query);
path_Query = path_Query.Replace(extension, string.Empty);// This will remove extension
You need to find the position of the first /, and then calculate the portion you want:
string url = "www.example.com/aaa/bbb.jpg";
int Idx = url.IndexOf("/");
string yourValue = url.Substring(Idx + 1, url.Length - Idx - 4);
Try This:
int positionOfJPG=url.IndexOf(".jpg");
string newString = url.Substring(18, url.Length - positionOfJPG);
string newString = url.Substring(18, (url.LastIndexOf(".") - 18))
Here is another suggestion. If you can prepend http:// to your url string you can do this
string path = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(path);
string expectedString =
uri.PathAndQuery.Remove(uri.PathAndQuery.LastIndexOf("."));
You need to check your statement like this :
string url = "www.example.com/aaa/bbb.jpg";
string lenght = url.Lenght-4;
if(url.Lenght > 15)//eg 15
{
string newString = url.Substring(18, lenght);
}
Can you try this ?
string example = url.Substring(0,(url.Length > 18 ? url.Length - 4 : url.Length))
I have the following:
string test = "9586-202-10072"
How would I get all characters to the right of the final - so 10072. The number of characters is always different to the right of the last dash.
How can this be done?
You can get the position of the last - with str.LastIndexOf('-'). So the next step is obvious:
var result = str.Substring(str.LastIndexOf('-') + 1);
Correction:
As Brian states below, using this on a string with no dashes will result in the original string being returned.
You could use LINQ, and save yourself the explicit parsing:
string test = "9586-202-10072";
string lastFragment = test.Split('-').Last();
Console.WriteLine(lastFragment);
I can see this post was viewed over 46,000 times. I would bet many of the 46,000 viewers are asking this question simply because they just want the file name... and these answers can be a rabbit hole if you cannot make your substring verbatim using the at sign.
If you simply want to get the file name, then there is a simple answer which should be mentioned here. Even if it's not the precise answer to the question.
result = Path.GetFileName(fileName);
see https://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
string tail = test.Substring(test.LastIndexOf('-') + 1);
YourString.Substring(YourString.LastIndexOf("-"));
With the latest C# 8 and later you can use Range Indexer as follows:-
string test = "9586-202-10072"
var foo = test?[(test.LastIndexOf('-') + 1)..];
// foo is => 10072
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");
if (indexOfHyphen >= 0)
{
string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
Console.WriteLine(contentAfterLastHyphen );
}
See String.lastIndexOf method
I created a string extension for this, hope it helps.
public static string GetStringAfterChar(this string value, char substring)
{
if (!string.IsNullOrWhiteSpace(value))
{
var index = value.LastIndexOf(substring);
return index > 0 ? value.Substring(index + 1) : value;
}
return string.Empty;
}
test.Substring[(test.LastIndexOf('-') + 1)..]
C# 8 (late 2019) introduces range operator and simplifies it a bit further. The two dots here means from the index (inclusive) till the end of string.
test.Substring(test.LastIndexOf("-"))
and... in case you need the left part of a string:
private string AllTheLeftPart(string theString)
{
string rightPart = theString.Substring(theString.LastIndexOf('-') + 1);
string leftPart theString.Replace("-" + rightPart, String.Empty);
return leftPart ;
}