Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate C char*?

Tags:

c

string

char

As simple as that. I'm on C++ btw. I've read the cplusplus.com's cstdlib library functions, but I can't find a simple function for this. I know the length of the char, I only need to erase last three characters from it. I can use C++ string, but this is for handling files, which uses char*, and I don't want to do conversions from string to C char.

like image 225
erandros Avatar asked Jun 25 '11 20:06

erandros


2 Answers

If you don't need to copy the string somewhere else and can change it

/* make sure strlen(name) >= 3 */
namelen = strlen(name); /* possibly you've saved the length previously */
name[namelen - 3] = 0;

If you need to copy it (because it's a string literal or you want to keep the original around)

/* make sure strlen(name) >= 3 */
namelen = strlen(name); /* possibly you've saved the length previously */
strncpy(copy, name, namelen - 3);
/* add a final null terminator */
copy[namelen - 3] = 0;
like image 90
pmg Avatar answered Nov 15 '22 23:11

pmg


I think some of your post was lost in translation.

To truncate a string in C, you can simply insert a terminating null character in the desired position. All of the standard functions will then treat the string as having the new length.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char string[] = "one one two three five eight thirteen twenty-one";

    printf("%s\n", string);

    string[strlen(string) - 3]  = '\0';

    printf("%s\n", string);

    return 0;
}
like image 20
thelionroars1337 Avatar answered Nov 15 '22 22:11

thelionroars1337