How can I trim a string in BASIC?

1k Views Asked by At

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?

3

There are 3 best solutions below

1
On

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.

1
On

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.

0
On

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