String Manipulation in C / C++ – 1 : compute length of string
February 10, 2011 Leave a comment
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++) ;
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++) ;
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.