I have a String like this:
www.myserver.net/Files/Pictures/2014/MyImage.jpg
And I want to split it, so I get the Substring after the last occurence of /.
Which means I like to get MyImage.jpg
I tried it like this:
MsgBox(URL.Substring(URL.LastIndexOf("/"), URL.Length - 1))
But that wont work. Can someone help me out how to do this in VB.Net?
C# is also okay, after I've understood the logic, I can convert it myself.
Use System.IO.Path.GetFileName instead:
Dim path = "www.myserver.net/Files/Pictures/2014/MyImage.jpg"
Dim filename = System.IO.Path.GetFileName(path) ' MyImage.jpg
For the sake of completeness, you could also use String.Split or String.Substring:
filename = path.Split("/"c).Last()
' or
Dim lastIndex = path.LastIndexOf("/")
If lastIndex >= 0 Then
fileName = path.Substring(lastIndex + 1)
End If
But it is more error-prone and less readable.
Related
I have many strings that have numbers at the end. The numbers can be of any size, for example:
myvar123
mysecondvar3
mythirdvar219107
The strings can have numbers even inside the name, not only at the end.
for example:
my2varable123
some123variable9480395
I would need to replace any number at the END with a placeholder. (NOT those inside the varname.)
for example:
my2varable123 should become: my2variable%placeholder%
some123variable9480395 should become: some123variable%placeholder%
The only way that comes to my mind is to go through the string using .right() and remove the char if it is numeric until I find the first non numeric char. Then in the end append the placeholder, but it looks like a lot of work for a rather simply problem.
Is there a better way to do this?
You could use a Regex for this.
Dim str As String = "some123variable9480395"
Dim pattern As String = "\d+$"
Dim replacement As String = "%placeholder%"
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(str, replacement)
I have a string in VB:
url = "http://example.com/aa/bb/cc.html"
I want to trim this url to the last sub-folder so it becomes:
url = "http://example.com/aa/bb"
I need everything after the last "/" to be removed.
I am thinking of using the string.lastindexof("/") method but don't know how to continue from there.
use a combination of Substring and Lastindex of. Like this:
url.substring(0,url.lastindexof("/"))
might be that you need to substract 1 from the lastindexof("/") value, i always forget it^^
When working with an URL, consider using the Uri class. Then handling such cases become easy.
Create a Uri instance:
Dim url = new Uri("http://example.com/aa/bb/cc.html")
Then you can either do
Dim result = url.AbsoluteUri.Remove(url.AbsoluteUri.Length - url.Segments.Last().Length)
or something like
Dim result = new Uri(url, ".").AbsoluteUri
You could use String.Remove() to remove the unwanted part of the string:
Dim temp As String = "http://example.com/aa/bb/cc.html"
Dim index As String = temp.LastIndexOf("/"c)
Dim ret As String = temp.Remove(index, temp.Length - index)
I have a string, for example:
Dim str as string = xxxxxxxxxxxxxxxxxxxx£xxx£xxxx**£**xxxxxxxxxx
I want to remove £ surrounded from * which is always at a certain position (11th for instance) from the end. The whole string is a long one, always change in size and cannot be counted from the start. I cannot use Replace as well, there may be same characters at other positions that I do not wish to remove.
Solution:
Dim rst As String = str.Remove(str.Length - 11, 1)
Edit: Whoops, I dunno what I was thinking on that first part.
The correct version of the first part would be:
str = str.Substring(0, str.Len -13) + str.Substring(str.Len-11);
There also may be an overload for the String.Delete function that allows you to use a negative number to represent the number of characters from the end of the string -- I know that the C# equivalent does.
If its always going to be the 11th character from the end you can do this...
Dim strTargetString As String = "xxxYxxxxxxxxxx"
Dim strTargetString2 As String = "xxxxxxxYxxxxxxxxxx"
Dim strResult As String = Mid(strTargetString, 1, (Len(strTargetString) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)
Dim strResult2 As String = Mid(strTargetString2, 1, (Len(strTargetString2) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)
Note that String.SubString is a more modern approach than Mid, but I use it out of preference and example.
This is fairly straightforward with a regular expression replacement operation using look-ahead:
Dim str as String = "xxxxxxxxxxxxxxxxxxxx£xxx£xxxx£xxxxxxxxxx"
Dim str2 as String = Regex.Replace(str, "£(?=.{10}$)", String.Empty)
This will target a single character followed by any ten characters then the end of the string and replace it with the String.Empty value (or just "" if you'd prefer).
How can i get the string within a parenthesis with a custom function?
e.x. the string "GREECE (+30)" should return "+30" only
There are some different ways.
Plain string methods:
Dim left As Integer = str.IndexOf('(')
Dim right As Integer= str.IndexOf(')')
Dim content As String = str.Substring(left + 1, right - left - 1)
Regular expression:
Dim content As String = Regex.Match(str, "\((.+?)\)").Groups[1].Value
For the general problem, I'd suggest using Regex. However, if you are sure about the format of the input string (only one set of parens, open paren before close paren), this would work:
int startIndex = s.IndexOf('(') + 1;
string result = s.Substring(startIndex, s.LastIndexOf(')') - startIndex);
With regular expressions.
Dim result as String = System.Text.RegularExpressions.Regex.Match("GREECE (+30)", "\((?<Result>[^\)]*)\)").Groups["Result"].Value;
Code is not tested, but I expect only compilation issues.
You could look a regular expressions, or otherwise play with the IndexOf() function
In Python, using the string index method and slicing:
>>> s = "GREECE(+30)"
>>> s[s.index('(')+1:s.index(')')]
'+30'
FromIp contains "192.168.1.1". I want to get the last number, but I can't figure out what's wrong here:
Dim str As String
str = FromIP.Text.Substring(FromIP.Text.LastIndexOf("."), FromIP.Text.Length).ToString()
MessageBox.Show(FromIP.Text.Length)
Eduardo has given the correct way of getting the substring - my answer here will just explain why the existing one fails.
String.Substring(int, int) takes a starting position and a count. You're basically saying, "Go from position 9 for 10 characters". The documentation explicitly states it will throw:
ArgumentOutOfRangeException [if]
startIndex plus length indicates a
position not within this instance.
-or-
startIndex or length is less than
zero.
Tested code:
Dim FromIp As String = "192.168.1.1"
Dim str As String
str = FromIp.Substring(FromIp.LastIndexOf(".") + 1).ToString()
MessageBox.Show(str)
You must add 1 to LastIndexOf to skip the dot
There no need put the lenght of the Substring when you want all the rest of the string
But this refactored code will work better:
Dim FromIp As String = "192.168.1.1"
Dim IpPart As String() = FromIp.Split(".")
MessageBox.Show(IpPart(3))
FromIP.Text.LastIndexOf(".") + 1
instead of
FromIP.Text.LastIndexOf(".")
and
FromIP.TextLength-FromIP.Text.LastIndexOf(".")
is the last parameter instead of
FromIP.TextLength
As far as I remember, Substring takes Start,Stop as parameters.
So that would be: txt.Substring(IndexOf, txt.Length - IndexOf) or just with one parameter: Substring(IndexOf + 1)