显示在这个方案相邻对的总数 [英] Displaying the total number of adjacent pairs in this program

查看:99
本文介绍了显示在这个方案相邻对的总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定的输入的char [] 我想找到字符串中的离散对数。因此对于一个输入:


  • DDDD输出2双

  • DDD输出为1对

  • DD输出为1对

  • D输出0对

每对中的字符必须是相邻的。对于ABCA输出仍然是0,因为'A'是不相邻。<一个输入href=\"http://stackoverflow.com/questions/32692645/displaying-the-total-number-of-adjacent-pairs-in-this-program?#comment53229099_32692645\">*

目的是找到字符串中对的总数。所以对于aaxbb输出应为2. <一个输入href=\"http://stackoverflow.com/questions/32692645/displaying-the-total-number-of-adjacent-pairs-in-this-program?#comment53241307_32692645\">*

有关我的输入字符串一个烧焦[] =dppccddd有3个对相邻的字母,但的我的程序的输出为4 。我该如何解决这个问题?

  INT I = 0,计数= 0,COUNT1 = 0;对于(i = 0; I&LT; = 6;我++)
{
    如果(A [I] ==一个第[i + 1])
    算上++;
}
的printf(%D,计数);


解决方案

只是为了让你的code稍微好一点,
而不是硬编码的6值,可以使用为(i = 0; I&LT;的sizeof(A)/ sizeof的(A [0]) - 1,我++)
要获得一个数组的一些元素。

与code的问题是,如果两个字符相匹配,它将再次开始从第二个比较,你需要跳过这个角色,所以增加 I 1

 如果(A [I] ==一个[我+ 1]){
    ++计数;
    ++我;
}

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

解决方案

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

这篇关于显示在这个方案相邻对的总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆