Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c - Displaying the total number of adjacent pairs in this program

Given an input char[] I would like to find the number of discrete pairs in the string. So for an input of:

  • "dddd" the output is 2 pairs
  • "ddd" the output is 1 pair
  • "dd" the output is 1 pair
  • "d" the output is 0 pairs

The characters in each pair must be adjacent. For an input of "abca" the output is still 0 because the 'a's are not adjacent.*

The goal is to find the total number of pairs in the string. So for an input of "aaxbb" the output should be 2.*

For my input string of char a[] = "dppccddd" there are 3 pairs of adjacent letters but my program's output is 4. How do I solve the problem?

int i = 0, count = 0, count1 = 0;

for (i = 0; i <= 6; i++)
{
    if (a[i] == a[i + 1])
    count++;
}
printf("%d", count);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just to make your code slightly better, instead of hardcoding value of 6, use for(i = 0; i < sizeof(a) / sizeof(a[0]) - 1; i++) To get a number of elements in an array.

The problem with your code is that if two chars are matched, it will start comparing from the second one again, you need to skip that character, so increase i by 1:

if(a[i] == a[i + 1]) {
    ++count;
    ++i;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...