WLVL Posted June 30, 2019 Share Posted June 30, 2019 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? Quote Link to comment Share on other sites More sharing options...
ikoon Posted June 30, 2019 Share Posted June 30, 2019 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 4 Quote Link to comment Share on other sites More sharing options...
acey195 Posted August 29, 2022 Share Posted August 29, 2022 (edited) Yup array slicing is awesome ^^ I'm wondering though, for when I actually cast a string to a character array (or string array, as chars don't exist in hou) it seems to error unfortunately. Of course I could just loop through the entire string to build the array.. but is there also an elegant way to do it? example of working, but "unelegant" code : string test = "Lorem ipsum"; int n = len(test); string charArray[]; resize(charArray, n); for(int i = 0; i < n; i++) charArray[i] = test[i]; printf("%s\n", charArray); Edited August 29, 2022 by acey195 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.