将字符串转换为字符数组

Convert a string into a char array

本文关键字:字符 数组 转换 字符串      更新时间:2023-10-16

c++新手,所以这是我正在做的一个项目的一部分,取一个字符串并打印最常用的数字以及它被使用的次数。我认为这是对的,但由于某种原因,我的字符数组不会被读取。关于如何修复有什么提示或建议吗?

#include <string>
#include <iostream>
using namespace std;
char getMostFreqLetter(string ss);
int main() {
    string s; //initilizing a variable for string s
    s = ("What is the most common letter in this string "); // giving s a string
    getMostFreqLetter(s); // caling the function to print out the most freq Letter
    return 0;
}
char getMostFreqLetter(string ss) {
    int max, index, i = 0;
    int array[255] = {0};
    char letters[];
    // convert all letters to lowercase to make counting letters non case sensative
    for (int i = 0; i < ss.length(); i ++){
        ss[i] = tolower(ss[i]);
    }
    //read each letter into
    for (int i = 0; i < ss.length(); i ++){
        ++array[letters[i]];
    }
    //
    max = array[0];
    index = 0;
    for (int i = 0; i < ss.length(); i ++){
        if( array[i] > max)
        {
            max = array[i];
            index = i;
        }
    }
    return 0;
}

如果你不认为空格是字母

那么更有效的方法应该是

vector<int> count(26,0);
for (int i = 0; i < s.length(); i++) {
    int range = to_lower(s[i])-'a';
    if ( range >= 0 && range < 26)
        count[range]++;
}
// Now you can do fix the max while iterating over count;

使用string::c_str()。将字符串转换为字符数组。

您的代码中有一些错误。

首先,字符数组letters完全未被使用。你应该忽略它,迭代字符串ss,这是我认为你打算做的。

这将改变你的第二个for循环从++array[letters[i]];++array[ss[i]];

其次,最后一个for循环有bug。您使用i作为索引来查找数组中的频率,而您需要使用字符的ascii值(ss[i])代替。下面是一个带有注释的固定版本:

    index = ss[0];
    max = array[index];
    for (int i = 0; i < ss.length(); i ++){
        if(!isspace(ss[i]) && array[ss[i]] > max)
        {
            max = array[ss[i]];   // you intended to use the ascii values of the characters in s to mark their place in array. In you code, you use i which is the just the index of the character in s as opposed to the ascii value of that character. Hence you need to use array[ss[i]].
            index = ss[i];
        }
    }
    return index;

一旦你做了上面的改变,当你在你的字符串上运行时,你会得到以下输出:

Most freq character: t