I have a Str5 set up like this:

Code:
FirstThing,SecondThing,ThirdThing,FourthThing

I have a variable, S, that contains a number. What I want to do is have some code that gets the nth string out of string 5 and into Ans. Each "Substring" is separated by a comma.

Ex.
S=2
Output= SecondThing

Thanks in advance.

Code:

1->A
inString(Str5,","->B
For(C,2,S
B+1->A
inString(Str5,",",Ans->B
End
If not(B
1+length(Str5->B
sub(Str5,A,B-A


This will extract element S from the Str5 and put the result in Ans.
Let me explain Jonbush's code a bit, to make sure you understand it well enough to apply the concepts yourself. The basic idea of this code is to look for the commas that delimit the items in your string using the inString( command, which returns the index of the next instance of the substring for which you're searching.

Code:
1->A
inString(Str5,","->B
Find the start (A) and end (B) of the first element of the encoded list. It simply starts at character 1, because that's the beginning of the string. Look for the end of the 1st item (specifically, the first character after the last character of the element), and store that index in B.

Code:
For(C,2,S
B+1->A
inString(Str5,",",Ans->B
End
Repeat this process until you get to the Sth element of the list. Note that for S=1, this loop won't run at all, because TI-BASIC checks the end condition (C <= S) before the first iteration. Within this string, set the character after the comma after the previous element as the first character of this element, then use inString( again to find the comma after this element.

Code:
If not(B
1+length(Str5->B
Special case for the last element of the list: inString( returns 0 if there are no more instances of the search substring in the string. In this case, the comma after the last element /would/ be at the first character after the end of the string, if there was one.

Code:
sub(Str5,A,B-A
Finally, actually plucks out the substring in question and puts it in Ans.
Thanks jonbush and KermMartian, the code worked great. I will be sure to give you credit when (or if Razz ) I finish the program. Thanks for your help.
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement