我应该创建一个程序,它创建一个带有常量 char 数组缩写的数组。虽然我的程序不会返回任何错误,但它也不会在我的某些 printf 位置打印任何字符。因此,我认为我的程序无法正常工作,并且它没有用任何字符填充我的数组。
void abbrev(const char s[], char a[], size_t size) {
int i = 0;
while (*s != '\0') {
printf('%c', *s);
if (*s != ' ' && *s - 1 == ' ') {
a[i] = *s;
i++;
printf('%c', a[i]);
}
s++;
}
}
void main() {
char jordan1[60] = " Electronic Frontier Foundation ";
char a[5];
size_t size = 5;
abbrev(jordan1, a, size);
system("PAUSE");
}
实际结果是什么都没有。至少我这么认为,因为我的控制台没有显示任何内容。结果应该是“EFF”,并且 size_t 大小应该限制我的字符数组 a,以防缩写太长。因此,它应该只实现字母,直到我的数组已满,然后是“\0”,但我还没有实现它,因为我的程序显然根本没有填充数组。
最佳答案
#include <stdio.h>
#include <ctype.h>
/* in: the string to abbreviate
out: output abbreviation. Function assumes there's enough room */
void abbrev(const char in[], char out[])
{
const char *p;
int zbPosOut = 0; /* current zero-based position within the `out` array */
for (p = in; *p; ++p) { /* iterate through `in` until we see a zero terminator */
/* if the letter is uppercase
OR if (the letter is alphabetic AND we are not at the zero
position AND the previous char. is a space character) OR if the
letter is lowercase and it is the first char. of the array... */
if (isupper(*p) || (isalpha(*p) && (p - in) > 0 && isspace(p[-1]))
|| (islower(*p) && p == in)) {
out[zbPosOut++] = *p; /* ... then the letter is the start letter
of a word, so add it to our `out` array, and
increment the current `zbPosOut` */
}
}
out[zbPosOut] = 0; /* null-terminate the out array */
}
这段代码在几行中说明了很多内容。我们来看看:
isupper(*p) || (isalpha(*p) && (p - in) > 0 && isspace(p[-1]))
|| (islower(*p) && p == in)
如果当前字符 (*p
) 是大写字符,或者是字母 c (isalpha(*p)
且前一个字符 p[- 1]
是一个空格,那么我们可以认为 *p
是单词的第一个字符,并且应该将其添加到我们的 out
数组中。包含测试 (p - in) > 0
因为如果 p == in
,那么我们位于数组的零位置,因此 p[-1 ]
未定义。
这个表达式中的顺序非常重要。如果我们将 (p - in) > 0
放在 isspace(p[-1])
测试之后,那么我们就不会利用 &&
运算符的惰性:一旦遇到 false 操作数,就不会计算后面的操作数。这很重要,因为如果 p - in == 0
,那么我们不想计算 isspace(p[-1])
表达式。我们编写测试的顺序可确保在确保我们不在零位置之后评估 isspace(p[-1])
。
最终表达式(islower(*p) && p == in)
处理第一个字母为小写的情况。
out[zbPosOut++] = *p;
我们将字符*p
附加到out
数组中。 out
的当前位置由 zbPosOut
变量跟踪,该变量随后递增(这就是为什么我们使用 postscript ++
而不是字首)。
测试abbrev
操作的代码:
int main()
{
char jordan1[] = " electronic frontier foundation ";
char out[16];
abbrev(jordan1, out);
puts(out);
return 0;
}
它给出 eff
作为输出。为了使其看起来像首字母缩略词,我们可以更改代码以将字母 *p
附加到 out
到:
out[zbPosOut++] = toupper(*p);
将添加到 out
数组中的每个字母大写(如果 *p
已经是大写,toupper
仅返回 *p
)。
关于c - 我的程序创建了一个字符数组的缩写,但不打印任何内容。我的错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55773707/