For lack of better things to do I went on coderbyte and did one of the simple challenges since I have not written code for a little while.
The problem was stated as following:
Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.
Few notes to TL;DR the comments:
- I would have used const std::string& but function definition was given by CoderByte
- string[string.length()] is guaranteed to return '\0' since C++11.
- My code does not look for any terminating zeroes.
I'm looking for more discussion regarding the structure, the approach to the problem and general look & feel.
This is my solution:
// The function definition was given by CoderByte, I would have used
// const std::string& if it was up to me
string LongestWord(string sen) {
// code goes here
int start = -1;
int bstart = -1;
int blen = 0;
// lequal since std string is compatible with c strings, it will have \0 at
// the end, saving a special case after the loop.
for (int i = 0; i <= sen.length(); ++i)
{
if (start == -1 && isalpha(sen[i]))
{
start = i;
}
else if (!isalpha(sen[i]))
{
if (start >= 0 && i - start > blen)
{
blen = i - start;
bstart = start;
start = -1;
}
}
}
return sen.substr(bstart, blen);
}
I ran the test cases and all was well, so I figured I'd check the top solution on the website:
string LongestWord(string sen) {
// code goes here
string sen2 = "";
for(int i=0;i<sen.length();i++)
{
if(isalpha(sen[i])||sen[i]==' '||'0'<=sen[i]&&sen[i]<='9')
{
sen2.append(sen.substr(i,1));
}
}
char* sench = (char*)sen2.c_str();
string longest = "";
int longestLen = 0;
for(const char* pch=strtok(sench," ");pch;pch=strtok(NULL," "))
{
if(strlen(pch)>longestLen)
{
longest = pch;
longestLen=strlen(pch);
}
}
return longest;
}
From my point of view my solution is less complicated, has fewer moving parts, is easier to digest and at first glance I expect it to perform better due to less looping(although I have not tested this).
I feel like I am missing something, this happens with some frequency where I notice people use more complex solutions and I wonder if I'm basically writing tutorial code or something. Is this just me doubting myself or have I missed something?
std::string
isn't compatible with c strings the way you seem to think it is.std::string
can contain several null characters. See: akrzemi1.wordpress.com/2014/03/20/strings-length \$\endgroup\$std::string
is probably always null terminated under the hood but the ending null character doesn't have the same meaning as in a C string: it's more convenient with thec_str()
interface, but doesn't prevent astd::string
to contain intermediary null characters. \$\endgroup\$