Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何计算一个文本字符串中有多少个不同的字母?_C_String_Diff_Letters - Fatal编程技术网

C 如何计算一个文本字符串中有多少个不同的字母?

C 如何计算一个文本字符串中有多少个不同的字母?,c,string,diff,letters,C,String,Diff,Letters,如何计算一个文本字符串中有多少个不同的字母 创建一个名为uniqueLetters的字符数组和一个名为currentLetter的字符。创建一个for循环,将currentLetter逐个设置为字符串中的每个字符。在我描述的第一个循环中嵌套另一个for循环,该循环检查currentLetter是否在uniqueLetters数组中。如果不在uniqueLetters数组中,则将其添加到uniqueLetters数组中。最后,计算uniqueLetters数组的长度 需要记住的一点是,“s”和“s

如何计算一个文本字符串中有多少个不同的字母

创建一个名为uniqueLetters的字符数组和一个名为currentLetter的字符。创建一个for循环,将currentLetter逐个设置为字符串中的每个字符。在我描述的第一个循环中嵌套另一个for循环,该循环检查currentLetter是否在uniqueLetters数组中。如果不在uniqueLetters数组中,则将其添加到uniqueLetters数组中。最后,计算uniqueLetters数组的长度

需要记住的一点是,“s”和“s”被认为是不同的字符。如果要将它们计算为相同的字母,则需要添加额外的逻辑来检查uniqueLetter数组中是否存在字母的小写或大写版本


希望这有帮助

实际上,这很简单:只需跟踪字符串中已经遇到的字符

const char *str = "foo bar baz quirk qux";

bool found[1 << CHAR_BIT] = { 0 };

int n_distinct = 0;

for (const char *p = str; *p; p++) {
    unsigned char ch = *p;

    if (!found[ch]) {
        n_distinct++;
        found[ch] = 1;
    }
}

printf("Distinct characters: %d\n", n_distinct);

Google确定C字符串中不同字符的数量。浏览前10个链接以获取想法。根据你的发现实施一些事情。你必须至少尝试一些东西,然后答案对你来说才有意义+1用于简单的n_计数。注意:在深奥的系统中,如果sizeofint==sizeofchar然后是1@chux,这是完全正确的,您建议我使用什么来代替?首先,我考虑强制转换为size_t1,但同样,也可能是sizeofsize_t==sizeofchar,因此……如果sizeofint==sizeofchar,则find[]数组方法可能无法使用-数组太大了。但是对于一个字符位为8或9的合理系统来说,这是一个很好的方法。@chux同时,我们只希望OP使用一个合理的实现:P