String Manipulation in C / C++ – 1 : compute length of string

Let us look at a few coding questions involving manipulation of character strings in C / C++.

Question 1. We are given a string and want to compute its length.

Solution. One method would be to use the strlen function from the string header. Otherwise, we can write our own function to perform the same task as follows:

—-

size_t length ( const char* s )

{

for (int i = 0; s[i] ! = 0; i++) ;

return i;

}

—-

That was simple enough, and in case one wishes to code using pointer instead of array notation, we could proceed as follows:

—-

size_t length (const char *s)

{

for (int i = 0; *s != 0; i++) ;

return i;

}

—–

Questions one would want to keep in mind while writing such code – does this work for extreme cases? i.e. what if the function is provided with an empty string as input? Would it work properly?

It is always essential to check to such cases whenever you writing code, especially if the code is a fragment of a much larger project, where one might not know where the input comes from and whereto the output goes.

—–

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: