# String Comparison

• 03-28-2010
mikeman
String Comparison
I'm attempting to compare two strings for use in insertion for a binary tree. I want to compare the strings similar to how integers are compared, I want the whole string compared, not character by character and returning a value once there is an inequality. How can I accomplish this? Can this method you're suggesting be incorporated to compare struct members? Like if (temp->data > current->data) ... ?

i.e.
Dan < dan < dane
• 03-28-2010
tabstop
If you've got strings (real strings, not fake strings), you can almost use < (I think the basic less-than will be case-sensitive, and not necessarily in a good way). Otherwise you write your own.

I also have no idea how you think "the whole string compared" and "character by character, returning a value once there is an inequality" could possibly be different, but oh well.
• 03-28-2010
mikeman
Quote:

Originally Posted by tabstop
If you've got strings (real strings, not fake strings), you can almost use < (I think the basic less-than will be case-sensitive, and not necessarily in a good way). Otherwise you write your own.

I also have no idea how you think "the whole string compared" and "character by character, returning a value once there is an inequality" could possibly be different, but oh well.

I don't think that you are right in the use of < or >, at least not in the sense I'm asking about.

It will, from what I can tell, compare character by character. Once an inequality is found, it will return the value. If that specific character is > or < the other character being compared, it returns + or - value.

I want to know about the entire string.

i.e.
On < March

If you just use < or >, it will show On > March. This is not true for my use. I want to essentially sum up the values (ascii) of each character of the strings, and compare these sums. This is what I meant by "whole string". I don't want a value returned as soon as str1[x] != str2[x].
• 03-29-2010
mikeman
I ended up just doing a workaround and using a loop to convert the strings to their ascii sums and comparing them that way.
• 03-29-2010
laserlight
That is not a workaround though. Based on your requirements, that is precisely what you should do.
• 03-29-2010
mikeman
I suppose so, yes ;) I was just thinking that there was an internal way of doing it that didn't require writing a separate function. Or perhaps I was just looking for confirmation that I had to do this and that's why things were going wrong.
• 03-29-2010
laserlight
Quote:

Originally Posted by mikeman
I was just thinking that there was an internal way of doing it that didn't require writing a separate function.

You could #include <numeric> and then use the return value of std::accumulate(str.begin(), str.end(), 0) for a given std::string str. You may also want to cache this value to avoid re-computing it for each comparison.