Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get substring in C

Tags:

c

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?

like image 713
shinshin32 Avatar asked Jul 13 '11 12:07

shinshin32


1 Answers

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.

like image 154
holgac Avatar answered Nov 12 '22 15:11

holgac