Search code examples
cstringchar

How to truncate C 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.


Solution

  • 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;