Search code examples
ti-basic

In TI-BASIC, how do I add a variable in the middle of a String?


I am wondering how to make something where if X=5 and Y=2, then have it output something like Hello 2 World 5.

In Java I would do String a = "Hello " + Y + " World " + X; System.out.println(a);

So how would I do that in TI-BASIC?


Solution

  • You have two issues to work out, concatenating strings and converting integers to a string representation.

    String concatenation is very straightforward and utilizes the + operator. In your example: "Hello " + "World" Will yield the string "Hello World'.

    Converting numbers to strings is not as easy in TI-BASIC, but a method for doing so compatible with the TI-83+/84+ series is available here. The following code and explanation are quoted from the linked page:

    :"?
    :For(X,1,1+log(N
    :sub("0123456789",ipart(10fpart(N10^(-X)))+1,1)+Ans
    :End
    :sub(Ans,1,length(Ans)-1?Str1
    

    With our number stored in N, we loop through each digit of N and store the numeric character to our string that is at the matching position in our substring. You access the individual digit in the number by using iPart(10fPart(A/10^(X, and then locate where it is in the string "0123456789". The reason you need to add 1 is so that it works with the 0 digit.

    In order to construct a string with all of the digits of the number, we first create a dummy string. This is what the "? is used for. Each time through the For( loop, we concatenate the string from before (which is still stored in the Ans variable) to the next numeric character that is found in N. Using Ans allows us to not have to use another string variable, since Ans can act like a string and it gets updated accordingly, and Ans is also faster than a string variable.

    By the time we are done with the For( loop, all of our numeric characters are put together in Ans. However, because we stored a dummy character to the string initially, we now need to remove it, which we do by getting the substring from the first character to the second to last character of the string. Finally, we store the string to a more permanent variable (in this case, Str1) for future use.

    Once converted to a string, you can simply use the + operator to concatenate your string literals with the converted number strings.

    You should also take a look at a similar Stack Overflow question which addresses a similar issue.