Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k 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 Reply

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...