C++,将数组中的重复实例返回到字符串

C++, return duplicate instances from an array to a string

本文关键字:实例 返回 字符串 数组 C++      更新时间:2023-10-16

背景:这不是家庭作业,它是基本 c++ 类的完全可选的复习。当我想通过时,我正在尽我所能地浏览每个示例,这个我非常坚持,现在已经持续了大约三个小时。

问题:编写一个函数以返回一个字符串,该字符串由 a 到 z 范围内的 10 x 10 小写字母字符数组的每一行中最常见的小写字母组成。

如果有多个最常用的字符,请使用按字母顺序排在前面的字符。

既不使用cin也不使用cout。

#include <iostream>
#include <string>
using namespace std;
string mostFrequent(char c[10][10]){
// this is the function I need to create
}
int main(){
char c[10][10] = {
'a','b','f','d','e','f','g','h','i','j',
'a','b','c','r','c','r','g','h','r','j',
'a','b','c','d','e','f','g','h','o','o',
'z','w','p','d','e','f','g','h','i','j',
'o','d','o','d','o','b','o','d','o','d',
'a','l','l','d','e','f','f','h','l','j',
'a','b','c','d','i','f','g','h','i','j',
'a','b','z','v','z','v','g','g','v','z',
'a','b','c','d','e','f','g','h','i','e',
'a','b','s','d','e','f','g','h','s','j',
};
cout << mostFrequent(c) << endl;
return 0;
}

因此,在为此的研究中,我发现了一些材料,这些材料允许我计算特定的 int 或 char 会在数组中出现多少次,但它不太适合问题的需要,因为它需要返回由最常见字符组成的字符串。见下文。

int myints[] = {10,20,30,30,20,10,10,20};

int mycount = std::count (myints, myints+8, 10);

因为它不起作用,所以我在考虑一个 for 循环,要逐行,我很可能需要将东西保存到数组中才能计数,但我完全不确定如何实现这样的东西。我什至考虑过使用阵列进行凯撒转移,但如果这是解决方案,我不确定该去哪里。

如果我正确理解了任务,你有一个矩阵 10x10,你必须创建一个长度为 10 的字符串,其中位置i处的字符是行i中字符中最常见的字符。

string mostFrequent(char c[10][10])  {
// The idea here is to find the most common character in each row and then append that character to the string
string s = "";
for (int i = 0; i < 10; i++) s += findMostFrequentCharacter(c[i]);
return s;
}

现在我们只需要实现一个函数char findMostFrequentCharacter(char c).我们将通过计算所有字符并选择最常用的字符来做到这一点(或者如果有多个最常见的字符,则按字母顺序排列):

char findMostFrequentCharacter(char c[10]) {
int counts[256]; // Assuming these are ASCII characters, we can have max 256 different values
// Fill it with zeroes (you can use memset to do that, but for clarity I'll write a for-loop
for (int i = 0; i < 256; i++) c[i] = 0;
// Do the actual counting
for (int i = 0; i < 10; i++) // For each character
counts[ c[i] ]++;  // Increase it's count by 1, note that c[i] is going to have values between 65 (upper case A) and 122 (lower case z)
char mostFrequent = 0;
// Find the one that is most frequent
for (char ch = 'A'; ch <= 'z' ch++) // This will ensure that we iterate over all upper and lower case letters (+ some more but we don't care about it)
if (counts[ch] > counts[c]) c = ch;  // Take the one that is more frequent, note that in case they have the same count nothing will happen which is what we want since we are iterating through characters in alphabetical order
return c;
}

我已经把代码写出来了,所以如果有任何编译错误,我很抱歉。