Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm currently learning C programming Language and I'm trying to understand this program here. Simply, the function squeeze out any char that match between s1 and s2. The thing that I don't understand though is the loop cycles. If I increment j (j++) after the first cycle of the second loop, the first char of s2 is not compared to the others in s1, but just with the first one of s1, right? Anyway the program works, but I just want to understand how it work out... Thanks in advance!

 void squeeze2(char s[], char t[]){
  int i, j, k;
  for(i = k = 0; s[i] != ''; i++){
    for(j = 0; t[j] != '' && t[j] != s[i]; j++)
      ;
    if(t[j] == '')
      s[k++] = s[i];
  }
  s[k] = '';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

The way this function works is that each character of s[] is compared with the the characters of t[]... The outer for loop goes through each character of s[] (as long '' is not encountered) and for each value in s[] the inner for loop compares it with each value of t[], as long as the end of t[] is not reached or a match is not found... In case the value of s[] for any value of i doesn't match with all values in t[] the second (inner) for loop will iterate to The value where t[j]='' which is checked by the following if statement and adds that particular value of s[] to the beginning/kth index (this will not mess up s[] as during the first cycle in case the first element of s[] doesn't match it shouldn't be there, that is value of k would remain the same for that element to get overwritten)... So... What you said is right... In the first cycle of second for loop the first element of t[] is compared with first element of s[] and for second cycle second element of t[] is compared with first element of s[] and so on...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...