涉及字符数组一个C语句含义 [英] Meaning of a C statement involving char arrays

查看:119
本文介绍了涉及字符数组一个C语句含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一种算法的一个项目,我碰到一些code,我觉得可能是有帮助跑去。然而,正如我尝试读取code,我有一些难以理解的code的声明。这里是code。

I am working on an algorithm for a project and I ran across some code that I think may be helpful. However, as I try to read the code, I am having some difficulty understanding a statement in the code. Here is the code.

int firstWord[MAX_WORD_SIZE] = {0}, c = 0;

while (word1[c] != '\0') //word1 is char[] sent as a parameter
{
  firstWord[word1[c]-'a']++;
  c++;
}

我理解(希望正确),第一行是建立我最大尺寸的整数数组,并使得初始计数器值C零沿元素初始化为零。

I understand (I hope correctly) that the first line is setting up an integer array of my max size, and initializing elements to zero along with making the initial counter value "c" zero.

据我了解,while循环遍历所有的字1 [] 数组的字符循环,直到它命中的最后字符'\\ 0

I understand that the while loop is looping through all of the characters of the word1[] array until it hits the final char '\0'

我就行了迷茫 firstWord [字词1 [C] - '一'] ++;
字1 [C] 应该给一个char,那么,是什么做的 - '一'吗?这是否投炭到一个整数,将允许您访问使用 firstWord [] 阵列和增量的元素 ++ ?如果是这样,哪一个元素或整数由字1给出[C] - '一'

I am confused on the line firstWord[word1[c]-'a']++; word1[c] should give a char, so what does doing the -'a' do? Does this cast the char to an integer which would allow you to access an element of the firstWord[] array and increment using ++? If so, which element or integer is given by word1[c]-'a'

推荐答案

这是一个计数的字母数的程序 A 以Z 从字。关键点在这里,'一' - '一' 0 的值,'b' - '一'有> 1

This is a program that counts the number of letters a to z from a word. The key point here is, 'a' - 'a' has a value of 0, and 'b' - 'a' has a value of 1, etc.

例如,如果字1 [C] 是字母D,那么'D' - '一' 3 ,所以会增加 firstWord [3] 。当这个词被字符重复字符, firstWord [3] 包含字母数D在字。

For instance, if word1[c] is the letter 'd', then 'd' - 'a' is 3, so it would increment firstWord[3]. When the word has been iterated character by character, firstWord[3] contains the number of letter 'd' in the word.

这篇关于涉及字符数组一个C语句含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆