سؤال

In the below code what does the statements str1[i] && str2[i]; and count1[str1[i]]++; do exactly ?

char str1[4]="rate";
char str2[4]="tear";

int count1[256] ;
int count2[256] ;

int i=0;

for (i = 0; str1[i] && str2[i];  i++)
{
   count1[str1[i]]++;//count1['g']++what does that mean ?
   count2[str2[i]]++;
}
هل كانت مفيدة؟

المحلول

for (i = 0; str1[i] && str2[i];  i++)

is the same as

for (i = 0; (str1[i] != 0) && (str2[i] != 0);  i++)

which is the same as

for (i = 0; (str1[i] != '\0') && (str2[i] != '\0';  i++)

Basically if any expression is used in a conditional statement, then the value is checked for boolean - true or false. If it's not a boolean - say it's an integral type, then 0 is false anything else is true.

Here str[i] is a char - which is an integral type. So if str[i] is 0, then it evaluates to false, else it evaluates to true.

For eg.

char c = 'A';

if(c)

is the same as

if (c != 0)

which is the same as

if (c != '\0')

c is 'A' (which in ascii is 65). 65 != 0, hence it evaluates to true & the if will be entered.

if instead, you have

char c = 0;

or

char c = '\0';

then c evaluates to 0. Hence if(c) evaluates to false & the if is not entered.

You can extend the same logic to str[i] which is an char.

If you have str1[]="rate", it's the same as str1[0] = 'r', str1[1] = 'a', str1[2] = 't', str1[3] = 'e', str1[4] = 0.

About the count1[str1[i]]++;

It's a count of how many times each character occurs - for eg. if the char set is ascii, then at the end of string traversal, count['A'] (which is the same as count[65]) will contain the number of times 'A' occurred in the string.

It will work only if each member of the count arrays are initialized to 0 somewhere (or they are global).

consider

str1[] = "ABAB";

count[str1[0]] is same as count['A'] which is same as count[65] (if char set is ascii).

The ++ will cause count['A'] to become 1

When i becomes 1, count[str1[1]]++ causes count['B'] to become 1. i = 2, then count['A'] becomes 2. i = 3, then count['B'] becomes 2.

نصائح أخرى

This algorithm counts the occurences of each ascii character in two strings simultaneously.

str1[i] && str2[i]

checks that the end of neither string is reached. count1[str1[i]]++ increases theo count of occurence of the character str1[i].

The && is applied to 2 characters, not strings. In this case it is checking that neither character is the null character.

for (i = 0; str1[i] && str2[i]; i++)
Loop runs for number of time smaller string length.
because ASCII value of '\0' is zero (0) , str1[i], or str2[i] zero means and of both zero and loop ends

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top