Just a quick question:
I have a string e.g.
char *str;
and I need a function that when called will truncate it shorter (gets rid of the end) or increase the length (fills the end with NULL).
Please can someone give me an example of how to do this. Thanks.
Comments
The answer to your first question is to simply put a 0 (or ' ') in the string position you wish that it ends at. For example:
char str[5] = "asdf";
str[2] = ' '; // ' ' is exactly equal to 0
printf ("%s
", str);
Will print "as" on the screen, since the 'd' character was replaced by the string terminator 0.
Your second question is a bit strange, since C doesn't work like that. A strings's length is defined by where the ' ' is (all characters after that are ignored), what do you mean increasing the string's length?
: Just a quick question:
:
: I have a string e.g.
:
: char *str;
:
: and I need a function that when called will truncate it shorter (gets rid of the end) or increase the length (fills the end with NULL).
:
: Please can someone give me an example of how to do this. Thanks.
:
:
: I have a string e.g.
:
: char *str;
:
: and I need a function that when called will truncate it shorter (gets rid of the end) or increase the length (fills the end with NULL).
:
: Please can someone give me an example of how to do this. Thanks.
:
Sounds like you want to use the realloc() function. It doesnt zero the bytes if you increase the size of the memory block (the string in this case) so you would have to call memset afterwards.