Question on a code segment

Aug 19, 2010 at 9:28pm
I have to update an existing code segment, which includes the following part:

1
2
3
4
5
6
7
8
9
10
11
int num[26]={0};
int index[26]={0};
char *s="abbbccdefafgg "; 

    int i;
    for(i=0;i<strlen(s);i++)
    {
        num[s[i]-'a']++;
        index[s[i]-'a']=i;
    }


But don't understand how do the following two lines of code work?

1
2
num[s[i]-'a']++;
        index[s[i]-'a']=i;


Thanks for helping me figuring out.
Aug 19, 2010 at 9:59pm
It looks like num holds the number of occurrences of a given letter in string s (each element represents a letter in the alphabet). a is zero, z is 25. index holds the index of the last element in s where a letter was found, using the same convention.

The s[i] - 'a' expression is meant to convert whatever value a is in ascii into 0, and so on. I'm not sure that whitespace is meant to be there, as the code only seems to be meant to work with lower case letters. It will probably cause an attempt to write outside the array.
Last edited on Aug 19, 2010 at 10:00pm
Aug 19, 2010 at 10:18pm
Hi, filipe:

Thanks for the reply, but I still feel confusing about the statement:
"The s[i] - 'a' expression is meant to convert whatever value a is in ascii into 0, and so on. "

say i=2, then s[i]=b, how s[i]-'a'is meant to convert whatever value a is in ascii into 0?

Aug 19, 2010 at 11:59pm
The s[i] - 'a' expression is meant to convert whatever value a is in ascii into 0, and so on.

So, in your example, s[i] - 'a' can be replaced with 'b' - 'a', which is 1.
Topic archived. No new replies allowed.