Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut out section of string

Tags:

c

string

pointers

I wouldn't mind writing my own function to do this but I was wondering if there existed one in the string.h or if there was a standard way to do this.

char *string = "This is a string";

strcut(string, 4, 7);

printf("%s", string); // 'This a string'

Thanks!

like image 203
Tyler Avatar asked Dec 23 '22 12:12

Tyler


2 Answers

Use memmove to move the tail, then put '\0' at the new end position. Be careful not to use memcpy - its behaviour is undefined in this situation since source and destination usually overlap.

like image 182
sharptooth Avatar answered Jan 13 '23 20:01

sharptooth


You can just tell printf to cut the interesting parts out for you:

char *string = "This is a string";
printf("%.*s%s", 4, string, &string[7]); // 'This a string'

:-)

like image 45
che Avatar answered Jan 13 '23 20:01

che