【问题标题】:Search for multiple occurrences of a value in a character array and then listing # of occurrences. VC++在字符数组中搜索多次出现的值,然后列出出现次数。 VC++
【发布时间】:2009-06-08 23:26:22
【问题描述】:

我正在尝试编写一个小程序,该程序将为从 ASCII 字符数组中提取的十六进制和二进制值生成奇偶校验位。我总共有 3 个字符数组。例如:

const char *caASCII[] = {"A", "B", "C", ...};

const char *caASCIIBinary[] = {"01000001", "01000010", "01000011", ...};

const char *caASCIIHex[] = {"41", "42", "43", ...};

所以,我输入“A”,它会在二进制和十六进制数组中找到相应的值,然后显示它们。我有一个线性搜索功能,可以进行搜索,而且效果很好。

我想知道是否可以计算,例如,“1”出现在一个二进制值中的次数,然后据此判断(如果 1 的数量是偶数或奇数)添加一个“ 0”或二进制值末尾的“1”。我想我必须将十六进制值除以 2 来查看它是偶数还是奇数。

我开始认为我必须将数组更改为不同的类型,可能是整数。关于如何解决这个问题的任何建议?

【问题讨论】:

    标签: c++ arrays


    【解决方案1】:

    三个数组的想法是一个巨大的废话:这些信息很容易通过很少的操作计算出来。 例如,要知道二进制表示中“1”的个数:

      int bits_on(char yourchar) {
        int count = 0;
        while (yourchar > 0) {
          count += yourchar % 2;
          yourchar >>= 1;
        }
        return count;
      }
    

    “如果是偶数就加 1”

    int newInt = yourChar << 1;
    newInt += bits_on(yourchar) % 2 == 0 ? 1 : 0;
    

    【讨论】:

      【解决方案2】:

      您只是在寻找一个计算字符的函数吗?您可以轻松地自己编写一个:

      size_t strcnt(const char *s, char c) {
        size_t count = 0;
        while (*s)
          if (*s++ == c) 
            count++;
        return count;
      }
      

      你会这样使用它:

      #include <iostream>
      // ...
      
      size_t count = strcnt(caASCIIBinary[2], '1')
      std::cout << count << " bits set in " << caASCIIBinary[2] << std::endl;
      

      【讨论】:

      • 我不确定我是否理解如何使用它。我假设我想指向其中一个数组,第二个变量是要搜索的字符?你能举例说明如何使用它吗?
      【解决方案3】:

      对于您的问题的方向答案,这会计算二进制字符串中 1 的数量:

      #include <algorithms>
      #include <string>
      
      const std::string caASCIIBinary[] = {"01000001", "01000010", "01000011", ...};
      
      int num_ones = std::count(caASCIIBinary[5].begin(), caASCIIBinary[5].end(), '1');
      

      如果您绝对坚持使用 char * 而不是字符串(不要这样做):

      int num_ones = std::count(caASCIIBinary[5], caASCIIBinary[5]+strlen(caASCIIBinary[5]), '1');
      

      但是,我不确定这是否是您真正想要做的。听起来,给定一个字符,您想输出一个附加了奇偶校验位的字符串:

      #include <bitset>
      #include <limits.h>
      #include <algorithms>
      using namespace std;
      
      string parity_string(char ch){
         string str(bitset<CHAR_BIT>(ch).to_string<char,char_traits<char>,allocator<char> >());
         if(count(str.begin(), str.end(), '1') % 2) { str.append("1"); }
         else { str.append("0"); }
         return str;
      }
      

      通过构造已附加奇偶校验位的位集可能是一种更简单的方法,但我必须考虑一下。

      编辑:Bam:

      string parity_string(char ch){
         bitset<CHAR_BIT+1> bs(ch);
         bs[CHAR_BIT] = bs.count() % 2;
         return bs.to_string<char,char_traits<char>,allocator<char> >();
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 2013-05-06
        • 2012-02-16
        • 2021-10-28
        • 1970-01-01
        • 2021-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多