Home > front end >  Remove first 10 characters from a string in C?
Remove first 10 characters from a string in C?

Time:06-29

I've got a string:

model name      : Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz

And I want to remove the first 10 characters, so that the start of the string would be the name of the CPU.

Essentially, how do I remove the first whitespaces, but not the ones in the actual name? Or, how do I remove the first 10 characters of this string?

CodePudding user response:

how do I remove the first 10 characters

Simply add 10 to your character pointer. Though in your example, you seem to actually need 18, not 10.

CodePudding user response:

You can use memmove to shift the contents of the string.

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

#define OFFSET 18

int main(void) {
    char string[] = "model name      : Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz";

    memmove(
        string,
        string   OFFSET,
        strlen(string)   1 - OFFSET);

    printf("<<%s>>\n", string);
}
<<Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz>>

CodePudding user response:

you can simply offset by 18 chars (not the 10 mentioned in the question) if you simply want to access the trailing part of the string.

 char * pointer_to_cpu = &longstring[18];

If you want to permanently erase them the memmove answer is what you need

CodePudding user response:

As an alternative to the other answers offered, if you need to save the string minus the first 10 characters as a separate item, without modifying the original:

strcpy(substr, &str[10]);

This assumes substr is a char array of sufficient size to avoid overflow.

  • Related