Begin to code
November 30, 2011 Leave a comment
I need to think about what kind of programming language I will use before writing codes.
If pick C, I need to consider how much memory I will need and declare that. It is dangerous to use undeclared memory.
If pick C++/Java ( I do not know much though), I should write code by C++-style ( containers, methods). C/C++ mixture is not a good habit.
This is a C/C++ mixture code. (dirty code)
string replaceStr(string str)
{
string strNew;
string::size_type nx=0;
for (string::size_type ox=0; ox != str.size(); ++ox)
{
if (str[ox] == ' ') // replace space with '%20'
{
strNew[nx++] = '%'; // error: assign value to empty string!!!!!
strNew[nx++] = '2';
strNew[nx++] = '0';
}
else
strNew[nx++] = str[ox];
}
return strNew;
}
This below is C++-style code (container). This piece of code is totally OK
string replaceStr(string str)
{
string strNew;
for (string::iterator iter = str.begin(); iter != str.end(); iter++)
{
if (*iter == ' ')
strNew += "%20";
else
strNew += *iter;
}
return strNew;
}