Reduce a string in C language

Asked

Viewed 821 times

5

How do I reduce the size of a string in C? In my program it is implemented as follows:

char nomeString[] = "nomedoarquivo.txt";

I intend to cut the ". txt" of the end of the string.

  • 1

    And what is the criteria? Do you have to find where this pattern is and cut? In what context is it used? Put your code.

  • The strings only have ". txt" at the end of them, I just wanted to cut these 4 characters at the end. charName[] = "filename.txt"; for: fileName[] = "filename";

1 answer

4


Like strings in C end with a null, just put a null right after the text that should stay. How to know that what should disappear are the last 4 characters just put the terminator in the size of the string minus 4. Thus:

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

int main(void) {
    char nomeString[] = "nomedoarquivo.txt";
    nomeString[strlen(nomeString) - 4] = '\0';
    printf("%s", nomeString);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Excellent, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.