Laurence
Laurence

Reputation: 7823

How to remove a character from at string at certain position from the end?

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)

Upvotes: 1

Views: 8779

Answers (3)

Phillip Schmidt
Phillip Schmidt

Reputation: 8818

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.

Upvotes: 1

lsuarez
lsuarez

Reputation: 4992

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).

Upvotes: 1

NoAlias
NoAlias

Reputation: 9193

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.

Upvotes: 1

Related Questions