Jump to content
WLVL

split a string into an array of characters in vex

Recommended Posts

I want to split a string after a specific number of characters.

ie. split after the 5th character (position 5)

string s = "0123456789";

into    

"012345" and "6789"

I don't have any consistent separator. I have a consistent amount of characters after which I want to split.

Split function won't work because by default it will set space as the separator if none is specified.

 

My approach would be.

Split the string into a characters array, and then recreate the separated strings using a for loop

string s_char[] => (0, 1, 2, 3 , 4, 5, 6 , 7, 8, 9)
int coord = 5; //coord to split at

string s_1, s_2;
for(int i; i <= coord; i++){
	s_1 += s_char[i];
}
for(int i; i>coord && i<max; i++){
	s_2 += s_char[i];
}

 

Any ideas on how to achieve this?

Share this post


Link to post
Share on other sites

Hi Davide, for strings and arrays, you can use the array[start:stop:step] syntax:

a[start:stop]  // items start through stop-1
a[start:]      // items start through the rest of the array
a[:stop]       // items from the beginning through stop-1
a[:]           // a copy of the whole array

For your case, this is the syntax:

int coord = 6;     // I changed the coord from 5 to 6
string s = "0123456789";

s@s_1 = s[:coord]; // "012345"
s@s_5 = s[coord:]; // "6789"

More examples and explanation here:

https://stackoverflow.com/questions/509211/understanding-slice-notation

a[-1]              // last item in the array
a[-2:]             // last two items in the array
a[:-2]             // everything except the last two items

//There is also the step value, which can be used with any of the above:
a[start:stop:step] // start through not past stop, by step

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×