| | |
How to improve program with string compairing?
![]() |
Hello ladies and gents,
I had to do an exercise in wich I was required to compair two standaardtype strings opposits, meaning: name = "Johan", name2 = "nahoJ"
The idea was to return a bool value True or False. I did this with the following code I wrote:
Alltough I managed to get 'a' solution, I was wondering if any of you could tell me how I could improve/shorten or make the code more clearly to follow
The idea is solely to try and code a program as best as possible.
Thanks for any assistance
I had to do an exercise in wich I was required to compair two standaardtype strings opposits, meaning: name = "Johan", name2 = "nahoJ"
The idea was to return a bool value True or False. I did this with the following code I wrote:
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <string> using namespace std; bool compair(const string &name, const string &name2) { int i, j; if (name.length() != name2.length())return false; for(i = name.length() - 1, j = 0;i >= 0 ;i--, j++) {if (name[i] != 0 name[j]) return false;} return true; } int main() { string name = "Johan", name2 = "nahoJ"; int c = compair(name, name2); if(c == 1) cout<<"True!"<<endl; else cout<<"False!"<<endl; cout<<"Press any key to continue!\n";cin.get(); return 0; }
Alltough I managed to get 'a' solution, I was wondering if any of you could tell me how I could improve/shorten or make the code more clearly to follow

The idea is solely to try and code a program as best as possible.
Thanks for any assistance
Is this right?
I might write it like this:
Generally, readability improves when every control structure uses braces and when operators have spaces on them. Also, string::size_type is an integer type that is guaranteed to be larger than any stored string. (It's just an unsigned long int on most systems, though: nothing terribly exciting.)
Also, it's a good idea to only use for loops of the form
or of the form
Or maybe even:
When you are not looping a single variable through a range of numbers, I consider it better form to use a while loop. You might find this to be the case also.
I might write it like this:
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <string> using namespace std; bool are_mirrored(const string &name, const string &name2); int main() { string name = "Johan", name2 = "nahoJ"; bool c = are_mirrored(name, name2); if (c) { cout << "True!" << endl; } else { cout << "False!" << endl; } cout << "Press any key to continue!\n"; cin.get(); return 0; } bool are_mirrored(const string &name, const string &name2) { if (name.size() != name2.size()) { return false; } string::size_type i = name.size(); string::size_type j = 0; while (i) { if (name[--i] != name2[j++]) { return false; } } return true; }
Generally, readability improves when every control structure uses braces and when operators have spaces on them. Also, string::size_type is an integer type that is guaranteed to be larger than any stored string. (It's just an unsigned long int on most systems, though: nothing terribly exciting.)
Also, it's a good idea to only use for loops of the form
C++ Syntax (Toggle Plain Text)
for (int i = m; i < n; ++i)
C++ Syntax (Toggle Plain Text)
for (int i = n; i > m; --i)
Or maybe even:
C++ Syntax (Toggle Plain Text)
for (string::iterator i = s.begin(); i != s.end(); ++i)
When you are not looping a single variable through a range of numbers, I consider it better form to use a while loop. You might find this to be the case also.
•
•
•
•
Originally Posted by Rashakil Fol
Is this right?
C++ Syntax (Toggle Plain Text)
if (name.size() != name2.size()) { return false; }
C++ Syntax (Toggle Plain Text)
while (i) { if (name[--i] != name2[j++]) ...
•
•
•
•
Also, string::size_type is an integer type that is guaranteed to be larger than any stored string.

string::size_type i = name.size()-1;
Thanks for the very usefull tips and improvements on my code Rashakil Fol :!:
•
•
•
•
Originally Posted by JoBe
Can you tell me why you prefer to use .size instead of .length?
•
•
•
•
Originally Posted by JoBe
Don't completly understand why you prefer to use this, but, I'll google to see what string::size_type just is
int is generally fine, too, on 32-bit systems, as long as strings are smaller than 2 million-something characters long.
•
•
•
•
Originally Posted by JoBe
Has to be -1, otherwise your comparing '\n'string::size_type i = name.size()-1;
Unless there's a bug. I have not compiled and run.
•
•
•
•
Originally Posted by Rashakil Fol
There's no '\0' character in the string. i starts after the end of the string because --i returns the decremented value of i, meaning that the first comparison uses the last character and first character of the respective strings. (Whereas i-- would return the original value of i.)
Unless there's a bug. I have not compiled and run.
Hmm strange
But, If I don't use it, it doesn't show the correct result :!: Here's an ever so minor nitpick.
Now it's nothing much when strings are short, but if such a function were used on something bigger and/or in a large loop, there is quite a bit of waste there. Let's say name is 1000 chars long: let's loop through 1000 chars to the end to find the length. Then later let's loop through 1000 chars to the end again to again find the length. A minor change would be to save the value and only calculate it once.
Nit-picky, yes. But it is helpful to always be thinking about such things as you code.
•
•
•
•
Originally Posted by Rashakil Fol
bool are_mirrored(const string &name, const string &name2) { if (name.size() != name2.size()) { return false; } string::size_type i = name.size(); string::size_type j = 0; while (i) { if (name[--i] != name2[j++]) { return false; } } return true; }
bool are_mirrored(const string &name, const string &name2)
{
string::size_type i = name.size();
if (i != name2.size()) {
return false;
}
string::size_type j = 0;
while (i) {
if (name[--i] != name2[j++]) {
return false;
}
}
return true;
} "One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
@ Dave, thanks for the tip on that, I think it's important not only to get your code working, but improve it where possible :!:
@ Rashakil Fol, now I know why you didn't need to use the -1, you used and I used
So, you subtracted 1 from i before you entered the loop.
@ Rashakil Fol, now I know why you didn't need to use the -1, you used
C++ Syntax (Toggle Plain Text)
--i
C++ Syntax (Toggle Plain Text)
i--
So, you subtracted 1 from i before you entered the loop.
•
•
•
•
Originally Posted by Dave Sinkula
Here's an ever so minor nitpick.
Now it's nothing much when strings are short, but if such a function were used on something bigger and/or in a large loop, there is quite a bit of waste there. Let's say name is 1000 chars long: let's loop through 1000 chars to the end to find the length. Then later let's loop through 1000 chars to the end again to again find the length. A minor change would be to save the value and only calculate it once.
The standard library's size() member function could look something similar to this (never mind that it really gets implemented in the basic_string class):
C++ Syntax (Toggle Plain Text)
string::size_type string::size() const { return end_ - beg_; }
And that would get inlined by a compiler -- making it one extra subtraction operation instead of one thousand-something operations. Only the C library's strlen function has to loop through the string, because C-style strings are simply pointers to arrays of characters that have a zero somewhere at the end.
And note that a compiler might have a mind to optimize any inefficiency away. It turns out that gcc will output identical-length executables
Last edited by Rashakil Fol; Jul 6th, 2005 at 8:06 pm. Reason: code tags
>length() was left in the string class for backwards compatibility with something
The string class existed in C++ before the STL was adopted, so length() was kept for backward compatibility with existing code and size() added in a poor attempt to make string more like a standard container.
>Also, size is four characters while length is six.
I find that hard to believe, since length() returns size(). Perhaps you're thinking of capacity(), in which case your suggestion is incorrect because the result of capacity() is largely implementation-dependent.
>You don't have to use it, and size_t will always work.
Chapter and verse, please.
>but either way, the size() function is guaranteed to be a constant-time operation.
Um, no. The standard says that size() "should" have constant complexity, not "shall" have constant complexity. That means that you can generally assume that calling size() is constant, but it's not guaranteed.
The string class existed in C++ before the STL was adopted, so length() was kept for backward compatibility with existing code and size() added in a poor attempt to make string more like a standard container.
>Also, size is four characters while length is six.
I find that hard to believe, since length() returns size(). Perhaps you're thinking of capacity(), in which case your suggestion is incorrect because the result of capacity() is largely implementation-dependent.
>You don't have to use it, and size_t will always work.
Chapter and verse, please.
>but either way, the size() function is guaranteed to be a constant-time operation.
Um, no. The standard says that size() "should" have constant complexity, not "shall" have constant complexity. That means that you can generally assume that calling size() is constant, but it's not guaranteed.
I'm here to prove you wrong.
•
•
•
•
Originally Posted by Narue
>Also, size is four characters while length is six.
I find that hard to believe, since length() returns size(). Perhaps you're thinking of capacity(), in which case your suggestion is incorrect because the result of capacity() is largely implementation-dependent.
![]() |
Other Threads in the C++ Forum
- Previous Thread: Game Programming
- Next Thread: small program request
| Thread Tools | Search this Thread |
addition api array base based binary bitmap c++ c/c++ char class classes code coding compile console conversion count delete deploy desktop developer directshow dll download dynamic dynamiccharacterarray email embed encryption error erroraftercompilation excel file forms fstream function functions game getline givemetehcodez gmail graph gui homework homeworkhelp homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker loop looping loops map math matrix matrix3d memory multiple news node output parameter pointer problem program programming project python random read recursion reference rpg std::coutwstring string strings temperature template test text text-file tree url variable vector video visualization win32 windows winsock word wordfrequency wxwidgets






