How to remove \n or \t from a given string in C?

后端 未结 5 1835
野性不改
野性不改 2021-01-18 01:27

How can I strip a string with all \\n and \\t in C?

5条回答
  •  青春惊慌失措
    2021-01-18 02:00

    Basically, you have two ways to do this: you can create a copy of the original string, minus all '\t' and '\n' characters, or you can strip the string "in-place." However, I bet money that the first option will be faster, and I promise you it will be safer.

    So we'll make a function:

    char *strip(const char *str, const char *d);
    

    We want to use strlen() and malloc() to allocate a new char * buffer the same size as our str buffer. Then we go through str character by character. If the character is not contained in d, we copy it into our new buffer. We can use something like strchr() to see if each character is in the string d. Once we're done, we have a new buffer, with the contents of our old buffer minus characters in the string d, so we just return that. I won't give you sample code, because this might be homework, but here's the sample usage to show you how it solves your problem:

    char *string = "some\n text\t to strip";
    
    char *stripped = strip(string, "\t\n");
    

提交回复
热议问题