How to truncate C char *?

So simple. I am in C ++ btw. I read the cplusplus.com cstdlib library functions, but I cannot find a simple function for this. I know the length of char, I only need to erase the last three characters from it. I can use a C ++ string, but this is for processing files that use char *, and I don't want to convert from string to C char.

+10
source share
6 answers

If you don’t need to copy the line somewhere else and you 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 is a string literal or you want to keep the original)

/* 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;
+23
source

I think part of your message was lost in translation.

C, . .

#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;
}
+6

, , :

const char* mystring = "abc123";
const int len = 6;

const char* substring = mystring + len - 3;

, substring , mystring, , mystring . , c , NULL .

, , , , .

+4
char * s = "1234567890";
s[5]='\0';

./compile: linia 2: 4113 Naruszenie ochrony pamięci (zrzut pamięci)./demo

!

: Google " ( )".

+1
bool TakeOutLastThreeChars(char* src, int len) {
  if (len < 3) return false;
  memset(src + len - 3, 0, 3);
  return true;
}

, , , . "NULL" 0.

0

, C char* "":

char, char *, \0 char ( 0).

,

char* str = "theFile.nam";

str+3 File.nam.

, - :

char str2[9];
strncpy (str2,str,8); // now str2 contains "theFile.#" where # is some character you don't know about
str2[8]='\0'; // now str2 contains "theFile.\0" and is a proper char* string.
0

All Articles