I have a string, let's say "THESTRINGHASNOSPACES".
I need something that gets a substring of 4 characters from the string. In the first call, I should get "THES"; in the second, I should get "TRIN"; in the third, I should get "GHAS". How can I do that in C?
If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);
or
for(int i=0; i<4; i++)
sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
sub3[i] = baseString[i+8];
sub3[4] = 0;
Prefer strncpy if possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With