Search code examples
cstringstring-length

Handle a string with length in C


In C (not C++), we can think several ways of handling strings with its length:

  • Just rely on the null terminating character (\0): We assume that the string doesn't contain \0. Store a string to a char array and append \0 at the end. Use the functions like strlen() when we need its size.

  • Store the characters and the length into a struct:

    typedef struct _String { char* data; int size; } String;

  • Use another variable for storing the length: For example,

    char name[] = "hello"; int name_size = 5; some_func(name, name_size, ...);

Personally, I prefer to use the second approach, since

  • It can cover some 'weird' strings which contain \0 in the middle.

  • We may implement some functions like string_new(), string_del(), string_getitem(), etc. to write some 'OOP-like' codes.

  • We don't have to two (or more) variables to handle the string and its length together.

My question is: What is the most-used way to handle strings in C? (especially: when we have to use a lot of strings (ex. writing an interpreter))

Thanks.


Solution

  • What is the most-used way to handle strings in C?

    No doubt the most common way by far is to simply rely on the null termination.

    Is it the "best" way? Probably not. Using a custom string library may be the "best" way as far as execution speed and program design are concerned. The downside is that you would have to drag that library around, since there are no standard or even de facto standard string libraries for C.