3

How do trim off characters in a string, by how much you want?

For example, say your string is "Tony", but you wanted to display "ny" by trimming of the first two characters, how can this be done?

Sub Main()

Dim s As String
Dim Result As String

s = "Tony"
Result = LTrim(s)

msgbox(Result)

I have this so far using the LTrim function, so how do you specify by how much you want to cut to just display "ny" in the MessageBox?

eoredson
  • 1,167
  • 2
  • 14
  • 29

3 Answers3

2

You don't want LTrim. You want Right:

Result = Right(s, Len(s) - 2);

This will take all but the two left-most characters of s.

jason
  • 236,483
  • 35
  • 423
  • 525
  • 1
    Appreciate the reply Michael, so say i wanted to cut 3 characters, the adjustment to the code would be Result = Right(s, Len(s) - 3) correct?? – user2634746 Aug 03 '13 at 02:53
1

You could use the additional string functions to do the same thing, for example:

X$ = RIGHT$(V$, 2) ' get the ending 2 chars of string
X$ = LEFT$(V$, 2) ' get the leading 2 chars of string
X$ = MID$(V$, 2, 2) ' get 2 chars from the inside of string
eoredson
  • 1,167
  • 2
  • 14
  • 29
0

Well... If I was trying to clip off the beginning of a string, I would use two functions: StrReverse, and Remove.

I would first reverse the string, then use the remove function to cut off what is now the end, Then flip the remaining string back to it's original state using the reverse function again.

The code would look something like this:

    Dim s As String = "Anthony"
    Dim index As Integer = 2

    Debug.Print(StrReverse(StrReverse(s).Remove(2)))

The output of this would be "ny" and the length will correspond to the index.

John Parker
  • 54,048
  • 11
  • 129
  • 129
nick
  • 425
  • 2
  • 4
  • 10
  • As per the [help section](http://stackoverflow.com/help), please don't add signatures/sign-offs on your questions or answers. – John Parker Aug 08 '13 at 08:06