Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to empty a C-String

Tags:

c

string

strcpy

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.empty().

I'm wondering what would be the proper way to empty a string in C. Would this be it?

 buffer[80] = "Hello World!\n";  // ...  strcpy(buffer, ""); 
like image 760
Benjamin Avatar asked Nov 12 '11 21:11

Benjamin


People also ask

How do I remove a character from a string in C?

We have removeChar() method that will take a address of string array as an input and a character which you want to remove from a given string. Now in removeChar(char *str, char charToRemove) method our logic is written.

How do you initialize a string to be empty?

std::string a; if(!a. empty()) { //You will not enter this block now } a = "42"; if(!a. empty()) { //And now you will enter this block. }

What is a null string in C How do you declare it?

Advertisements. Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello".


2 Answers

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)); 
like image 134
Mysticial Avatar answered Sep 22 '22 08:09

Mysticial


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 ;)

like image 24
Aiyion.Prime Avatar answered Sep 24 '22 08:09

Aiyion.Prime