只是从我的教科书中浏览一个单词频率计数程序,我正在
在理解几个细分方面有些麻烦。
我得到了函数的基本要点,我们从标准输入中得到一个字并返回
如果找到一个单词,则为1,否则为0。
现在,if (strchr(wordChars,ch)) break;
这行只是说:“如果字符
从stdin抓取是字母表的一部分,我们正在打破循环?
接下来,*c++ = ch;
这行使我感到困惑,这是设置第一个字符
到字符串的第二个元素?你为什么想做这个?
while ((ch = getchar()) != EOF) {
ch = tolower(ch);
if (!strchr(wordChars,ch)) break;
*c++ = ch;
这是功能的实质,对吗?我们构成实际单词的地方。也,
if (c == buf) return 0;
我假设这行是什么也没抓住的读取非字母输入。
这里的语法令人困惑,\是字符吗?在我看来,这
字符串的元素尚未初始化。如果我们离开那
代码的其余部分是我们将单词移回元素的位置,
对我来说真的没有意义。
if (buf[0] == '\'') {
for (c = buf+1; *c != '\0'; c++)
*(c-1) = *c;
*(c-1) = '\0';
}
接下来,这不是访问和替换吗
这个词的最后一个字母?这对我来说很有意义
如果strlen包含空字符,但这不对吗?
n = strlen(buf)-1;
我想我想从中得到的真正的东西是“\”的意思。
谢谢你的帮助!**
int getWord(char *buf){
int ch, n;
char *c = buf;
const char *wordChars = "abcdefghijklmnopqrstuvwxyz'";
while ((ch = getchar()) != EOF) {
ch = tolower(ch);
if (strchr(wordChars,ch)) break;
}
if (ch == EOF) return 0;
*c++ = ch;
while ((ch = getchar()) != EOF) {
ch = tolower(ch);
if (!strchr(wordChars,ch)) break;
*c++ = ch;
}
*c = '\0';
if (c == buf) return 0;
if (buf[0] == '\'') {
for (c = buf+1; *c != '\0'; c++)
*(c-1) = *c;
*(c-1) = '\0';
}
n = strlen(buf)-1;
if (buf[n] == '\'') {
buf[n] = '\0';
}
else if (buf[n-1] == '\'' && buf[n] == 's') {
buf[n-1] = '\0';
}
return 1;
}
最佳答案
哇,好多问题!我会尽力回答所有问题。Now, is 'if (strchr(wordChars,ch)) break;' this line just saying, "if the char we grabbed from stdin is part of the alphabet we're breaking the loop?
是。来自documentation:“如果找不到字符,则该函数返回空指针。”因此,如果在ch
中找不到wordChars
,则strchr
返回NULL
,它等于0
。Following, '*c++ = ch;' this line confuses me, is this setting the first character to the second element of the string? Why would you want to do this?
否。这将第一个字符设置为字符串的第一个元素,然后递增字符串指针。 (从技术上讲,这并不完全正确,实际上是指针在递增,但是操作员返回了旧的指针,这就是正在设置的指针。)这种情况反复发生,将新的ch
写入到字符串。Also, 'if (c == buf) return 0;' I'm assuming this line is to catch when nothing or a non-alphabetic input is read.
没错The syntax here is confusing, is \' a character? It would seem to me that this element of the string hasn't been initialized yet.
如果您键入'''
,编译器会怎么想?它将看到''
(这是一个无效字符(因为撇号之间没有任何内容)),然后看到另一个'
(将保持不匹配)。 \
是转义字符。 \'
的基本含义是“编译器,请勿将此撇号视为字符的结尾定界符-请将其视为字符!”If we leave that, the rest of the code is where we shift the word we got back an element, this doesn't really make sense to me.
基本上,您在这里所做的工作是从字符#1一直到单词的末尾,然后将字符逐一移回一个索引。然后,您必须使用\0
对字符串进行空终止。 (请注意,这里的\
也是转义字符。您可能需要查询一下以查看更多示例。Here是参考。)Next, isn't this accessing and replacing the last letter of the word? It would make sense to me if strlen include the null character, but it doesn't right?
它正在替换单词的最后一个字符。具体来说,它将用空终止符替换它,从而有效地删除了最后一个字符。基本上,这段代码和最后一部分只是从单词的开头和结尾删除撇号。
我希望这有帮助!请问您任何其他问题! :)
关于c - 语法和指针算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24965563/