Proper way to empty a C-String

前端 未结 6 1829
孤城傲影
孤城傲影 2020-12-04 15:12

I\'ve been working on a project in C that requires me to mess around with strings a lot. Normally, I do program in C++, so this is a bit different than just saying string.e

相关标签:
6条回答
  • 2020-12-04 15:57

    needs name of string and its length will zero all characters other methods might stop at the first zero they encounter

        void strClear(char p[],u8 len){u8 i=0; 
            if(len){while(i<len){p[i]=0;i++;}}
        }
    
    0 讨论(0)
  • 2020-12-04 15:59

    Depends on what you mean by emptying. If you just want an empty string, you could do

    buffer[0] = 0;
    

    If you want to set every element to zero, do

    memset(buffer, 0, 80);
    
    0 讨论(0)
  • 2020-12-04 16:07

    I'm a beginner but...Up to my knowledge,the best way is

    strncpy(dest_string,"",strlen(dest_string));
    
    0 讨论(0)
  • 2020-12-04 16:09

    It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.

    This will also work:

    buffer[0] = '\0';
    

    If you want to zero the entire contents of the string, you can do it this way:

    memset(buffer,0,strlen(buffer));
    

    but this will only work for zeroing up to the first NULL character.

    If the string is a static array, you can use:

    memset(buffer,0,sizeof(buffer));
    
    0 讨论(0)
  • 2020-12-04 16:13

    If you are trying to clear out a receive buffer for something that receives strings I have found the best way is to use memset as described above. The reason is that no matter how big the next received string is (limited to sizeof buffer of course), it will automatically be an asciiz string if written into a buffer that has been pre-zeroed.

    0 讨论(0)
  • 2020-12-04 16:14

    Two other ways are strcpy(str, ""); and string[0] = 0

    To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.

    #include <string.h>
    
    ...
    
    int i=0;
    for(i=0;i<strlen(string);i++)
    {
        string[i] = 0;
    }
    

    In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.

    At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.

    It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)

    I hope this was useful for anybody ;)

    0 讨论(0)
提交回复
热议问题