gpt4 book ai didi

c - 我如何扫描包含某人姓名的字符串并为其创建缩写?

转载 作者:行者123 更新时间:2023-11-30 18:52:01 25 4
gpt4 key购买 nike

所以基本上我需要从用户(用户名)获取输入,然后迭代用户名并创建一个新的缩写字符串。然后我必须输出缩写。我对如何在 C 中执行此操作感到非常困惑。

要记住的一件事是我必须使用指针。我无法按照作业说明中所述使用数组操作。我认为我走在正确的道路上,但我对如何将字符连接到字符串感到困惑。有人可以帮我吗?

这是到目前为止的代码:

#include <stdio.h>
#include <string.h>

int main() {
char *name = malloc(100);
char c[5];
char *initials = c;

printf("Enter your full name in the following format 'First Middle Last':\n");
fgets(name, 100, stdin);

for(int i = 0; i < strlen(name); i++){
if(name[i] == ' '){
strcat(&name[i + 1], initials);
printf("%s", initials);
}
}
}

谢谢!

示例输入:Charles Edwin Roberts

示例输出:C.E.R

最佳答案

我会手动扫描输入,当我找到单词的第一个字母时,将其大写版本复制到缩写数组中,并在后面添加一个点;单词的后续字母将被忽略;非字母将标记单词的结尾。

源代码(caps.c)

#include <ctype.h>
#include <stdio.h>

int main(void)
{
char name[100];
while (printf("Please enter the name (First Middle Last): ") > 0 &&
fgets(name, sizeof(name), stdin) != 0)
{
char *s = name;
int inword = 0;
unsigned char c;
char initials[20] = "";
char *p = initials;
char *e = initials + sizeof(initials) - 2;
while ((c = (unsigned char)*s++) != '\0')
{
if (!isalpha(c))
inword = 0;
else if (inword == 0)
{
*p++ = toupper(c);
*p++ = '.';
inword = 1;
if (p >= e)
break;
}
}
if (p > initials)
*(p - 1) = '\0'; /* Zap the final dot to meet the spec */

printf("Initials: %s\n", initials);
}
putchar('\n');
return 0;
}

我拒绝重复运行该程序,因此我添加了一个简单的循环。由于 printf() 返回它打印的字符数,因此 > 0 测试是安全的。如果您担心 I/O 包在从标准输入读取之前不会刷新标准输出,您可以将 && fflush(stdout) == 0 添加到循环条件。

示例运行

$ gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
> -Wold-style-definition -Werror caps.c -o caps
$ caps
Please enter the name (First Middle Last): Charles Edwin Roberts
Initials: C.E.R
Please enter the name (First Middle Last): john michael doe
Initials: J.M.D
Please enter the name (First Middle Last): john.m.doe
Initials: J.M.D
Please enter the name (First Middle Last): the artist formerly known as "prince"
Initials: T.A.F.K.A.P
Please enter the name (First Middle Last): he who has far too many words in his name was here
Initials: H.W.H.F.T.M.W.I.H
Please enter the name (First Middle Last): antiquated (old) man!!!
Initials: A.O.M
Please enter the name (First Middle Last): ajaykumar
Initials: A
Please enter the name (First Middle Last): @(#)$!!!
Initials:
Please enter the name (First Middle Last):
$

关于c - 我如何扫描包含某人姓名的字符串并为其创建缩写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35402472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com