根据用户输入的每个字母添加到数组索引

时间:2017-03-09 05:25:11

标签: c++ arrays string sorting

所以我试图创建一个尽可能短的函数:

  1. 将用户输入作为字符串输入并将其放入const char。
  2. 数组中
  3. 对于整个const char数组,使用for循环来获取for循环中当前索引的字母位置。
  4. 然后使用字母顺序作为索引,并在26个整数的数组中为该索引添加一个。
  5. 简而言之:它记录字符串中字符的频率并将其添加到整数数组中,因此如果我输入“ABC”,它将输出1,1,1,0,0等,或者如果我输入“XXYZZ”,它将输出... 0,0,0,2,1,2。

    我已经对此采取了一些措施,但似乎没有效果;

    void addCommonToArray(int alphabet_common[], string userinput) {
    
    const char * alphabet = userinput.c_str(); // String to array
    int index;
    
    for (int i = 1; i == sizeof(alphabet); i++) {
        index = alphabet[i] - 64; // Get current index and minus 64 from ascii code to get alphabetical order
        alphabet_common[index]++; // Add one to the position of the current index in the alphabet
    } }
    

    我已经多次修改但看起来不是问题,但alphabet_common数组是空白的。 (同样在main.cpp中有一个包含26个整数的数组,但是数组的所有元素都是0)所以这里的问题是数组保持为0。

    我感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我修好了,

void addCommonToArray(int alphabet_common[], string userinput) {
int index;
for (char& c : userinput) {
    index = toupper(c) - 64;
    alphabet_common[index]++;
} }

显然for循环甚至没有执行,但上面似乎都有效。