How to improve program with string compairing?

Reply

Join Date: Sep 2004
Posts: 421
Reputation: JoBe is on a distinguished road 
Solved Threads: 4
JoBe's Avatar
JoBe JoBe is offline Offline
Posting Pro in Training

How to improve program with string compairing?

 
0
  #1
Jul 6th, 2005
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:
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. bool compair(const string &name, const string &name2)
  7. {
  8. int i, j;
  9.  
  10. if (name.length() != name2.length())return false;
  11.  
  12. for(i = name.length() - 1, j = 0;i >= 0 ;i--, j++)
  13. {if (name[i] != 0 name[j]) return false;}
  14.  
  15. return true;
  16. }
  17.  
  18. int main()
  19. {
  20. string name = "Johan", name2 = "nahoJ";
  21.  
  22. int c = compair(name, name2);
  23.  
  24. if(c == 1)
  25. cout<<"True!"<<endl;
  26. else
  27. cout<<"False!"<<endl;
  28.  
  29. cout<<"Press any key to continue!\n";cin.get();
  30.  
  31. return 0;
  32. }

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
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 2,003
Reputation: Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice 
Solved Threads: 137
Team Colleague
Rashakil Fol's Avatar
Rashakil Fol Rashakil Fol is online now Online
Super Senior Demiposter

Re: How to improve program with string compairing?

 
0
  #2
Jul 6th, 2005
  1. if (name[i] != 0 name[j])
Is this right?

I might write it like this:

  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. bool are_mirrored(const string &name, const string &name2);
  7.  
  8. int main()
  9. {
  10. string name = "Johan", name2 = "nahoJ";
  11.  
  12. bool c = are_mirrored(name, name2);
  13.  
  14. if (c) {
  15. cout << "True!" << endl;
  16. } else {
  17. cout << "False!" << endl;
  18. }
  19.  
  20. cout << "Press any key to continue!\n";
  21. cin.get();
  22.  
  23. return 0;
  24. }
  25.  
  26. bool are_mirrored(const string &name, const string &name2)
  27. {
  28.  
  29. if (name.size() != name2.size()) {
  30. return false;
  31. }
  32.  
  33. string::size_type i = name.size();
  34. string::size_type j = 0;
  35.  
  36. while (i) {
  37. if (name[--i] != name2[j++]) {
  38. return false;
  39. }
  40. }
  41.  
  42. return true;
  43. }

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
  1. for (int i = m; i < n; ++i)
or of the form
  1. for (int i = n; i > m; --i)

Or maybe even:
  1. 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.
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 421
Reputation: JoBe is on a distinguished road 
Solved Threads: 4
JoBe's Avatar
JoBe JoBe is offline Offline
Posting Pro in Training

Re: How to improve program with string compairing?

 
0
  #3
Jul 6th, 2005
Originally Posted by Rashakil Fol
Is this right?
No, it's a typo


  1. if (name.size() != name2.size())
  2. {
  3. return false;
  4. }
Can you tell me why you prefer to use .size instead of .length?

  1. while (i)
  2. {
  3. if (name[--i] != name2[j++])
  4. ...
Man, this is a very very good tip, never thought about using a while loop and didn't even think that during the selection you could compare name with name2 by subtracting i and adding towards j during the while loop.

Also, string::size_type is an integer type that is guaranteed to be larger than any stored string.
Don't completly understand why you prefer to use this, but, I'll google to see what string::size_type just is

 string::size_type i = name.size()-1;
Has to be -1, otherwise your comparing '\n'

Thanks for the very usefull tips and improvements on my code Rashakil Fol :!:
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 2,003
Reputation: Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice 
Solved Threads: 137
Team Colleague
Rashakil Fol's Avatar
Rashakil Fol Rashakil Fol is online now Online
Super Senior Demiposter

Re: How to improve program with string compairing?

 
0
  #4
Jul 6th, 2005
Originally Posted by JoBe
Can you tell me why you prefer to use .size instead of .length?
All or almost all other standard library containers use size() exclusively. length() was left in the string class for backwards compatibility with something, according to my current unknowledgeable theory. Also, size is four characters while length is six.

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
Usually I'll just use size_t (which is an integer type large enough to contain the length of any old array). Using string::size_type just makes for more portable code (but this would have to be some bizarre, Star Trek-like pseudocomputer.) You don't have to use it, and size_t will always work. (The only situation where I imagine using string::size_type could ever actually matter is one where strings are for some reason stored in a different memory space than other objects.)

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
 string::size_type i = name.size()-1;
Has to be -1, otherwise your comparing '\n'
There's no '\n' 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.
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 421
Reputation: JoBe is on a distinguished road 
Solved Threads: 4
JoBe's Avatar
JoBe JoBe is offline Offline
Posting Pro in Training

Re: How to improve program with string compairing?

 
0
  #5
Jul 6th, 2005
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.
Euh, yes I ment '\0'

Hmm strange But, If I don't use it, it doesn't show the correct result :!:
Reply With Quote Quick reply to this message  
Join Date: Apr 2004
Posts: 4,309
Reputation: Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future 
Solved Threads: 228
Team Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: How to improve program with string compairing?

 
0
  #6
Jul 6th, 2005
Here's an ever so minor nitpick.
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;
}
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.
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;
}
Nit-picky, yes. But it is helpful to always be thinking about such things as you code.
"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
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 421
Reputation: JoBe is on a distinguished road 
Solved Threads: 4
JoBe's Avatar
JoBe JoBe is offline Offline
Posting Pro in Training

Re: How to improve program with string compairing?

 
0
  #7
Jul 6th, 2005
@ 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
  1. --i
and I used
  1. i--

So, you subtracted 1 from i before you entered the loop.
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 2,003
Reputation: Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice 
Solved Threads: 137
Team Colleague
Rashakil Fol's Avatar
Rashakil Fol Rashakil Fol is online now Online
Super Senior Demiposter

Re: How to improve program with string compairing?

 
0
  #8
Jul 6th, 2005
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.
This inefficiency is not actually the case. The standard library string class usually stores three pointers: One to the beginning of the string's array of characters, one to the end of the string's array, and one to the end of the string. (The string might not use all of its allocated space.) Some implementations might store one pointer and two size_t integers -- but either way, the size() function is guaranteed to be a constant-time operation.

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):

  1. string::size_type string::size() const
  2. {
  3. return end_ - beg_;
  4. }

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
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,540
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 704
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: How to improve program with string compairing?

 
0
  #9
Jul 6th, 2005
>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.
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 2,003
Reputation: Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice Rashakil Fol is just really nice 
Solved Threads: 137
Team Colleague
Rashakil Fol's Avatar
Rashakil Fol Rashakil Fol is online now Online
Super Senior Demiposter

Re: How to improve program with string compairing?

 
0
  #10
Jul 6th, 2005
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.
Four characters as in s-i-z-e. It's easier to code with shorter names.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC