Hi,
I would like to calculate the value between two strings. For example:
abc-aaa would be 29.
Did you mean 28? I'm going to assume that you want to treat
each string as a base-26 number with digits a=0,...,z=25; if that's
not your intent, please explain it more fully.
I tried:
printf("abc-aaa = %d\n","abc"-"aaa");
but I get -4.
You might have gotten almost anything, including herpes.
How can I do what I want?
A couple of ways, depending on what you already know about the
strings (e.g., will they always be of the same length, are they known
to be free of strange characters like '#', do you treat 'A' and 'a'
as equivalent, and so on). Here are a few sketches:
1) If the strings will always be of the same length, you could
march across them from left to right, comparing corresponding
characters. You'd find 'a'-'a' == 0, so you'd set delta=0.
At the next position you'd have 'b'-'a' == 1, and you'd set
delta = delta * 26 + 1 == 1. In the third position you'd get
'c'-'a' == 2, delta = delta * 26 + 2 == 28. Since the strings
are now exhausted, that's your final answer.
2) Method (1) has a flaw, because it assumes 'b'-'a' == 'c'-'b'
== ... == 'z'-'y' == 1. This is a very common scheme for
encoding letter values, but it is not universal. You could
salvage the method by looking up each character in a separate
string "abcdefghijklmnopqrstuvwxyz" and subtracting their
positions rather than their code values. The strchr() function
could be your friend here, and there are other possibilities too.
3) If the strings are of unequal length, you could pretend that the
shorter had a prefix of "aaa...aaa" to extend it to the length
of the longer. In this case it might be easier to work from
right to left and accumulate delta a little differently.
4) A sneaky possibility: The strtol() function can be made to
treat the string as a base-36 number, with a=10,...,z=35. You
could convert each string to a number this way, subtract them,
and then fiddle with the answer to correct the 36-vs-26 bias.
This approach treats 'A' and 'a' as the same.
5) All the above methods assume that the strings are not "too long."
If they get long enough so that their values or differences
exceed the capacity of your machine's numbers, you'll need to get
more imaginative. For most machines strings of up to length 6
will be all right, while longer strings may encounter trouble.
With very little effort you could push the upper limit to 13, but
beyond that you'd have a good deal more work to do.
However, I have a sneaking suspicion that your current level of
expertise in C might not be adequate for any of these approaches. This
is not a slight on your character (there's no shame in starting to learn
something new to you), but I really, really think you should spend some
more time with your C textbook before you try to go much further.