c - 如何在 C 中缩写全名?

标签 c arrays string algorithm function

<分区>

我正在尝试从用户那里获取全名并显示他的姓名缩写,类似这样:

“Edward Cantrell Cavender Davis” --> Name the user entered

"DAVIS, E. C. C.” -- Name abbreaviated

问题是我不知道该怎么做,我是 C 语言的新手,我在想是否有一些库可以做到这一点。

用户可以输入的最大名称是200,我需要通过一个函数来检查这个并显示缩写的名称。

我的代码:(我卡在这里了)

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

void name_abbreviated (char name[200]) {

}

int main() {
    char name[200];
    printf("Type a full name : ");
    gets(name);
    name_abbreviated(name);
}

最佳答案

I am thinking if there some library that does this

不,没有。您必须编写自己的代码才能实现此目的。


我可以使用的算法如下:

  1. 找到最后一个空格(标记其索引)并提取姓氏。
  2. 遍历 name,直到空白(你有索引 已经)。每次遇到空格,存储首字母 单词放入缓冲区。

代码:

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

#define LEN 200

void name_abbreviated (char name[]) {
    //printf("|%s|\n", name);
    char last_name[20];
    int j = 0, last_space_idx;
    for(int i = strlen(name) - 1; i >= 0; --i)
    {
        if(name[i] == ' ')
        {
            last_space_idx = i;
            while(name[i])
                last_name[j++] = name[++i];
            last_name[j] = '\0';
            break;
        }
    }
    //printf("|%s|\n", last_name);
    char rest_name[15];
    rest_name[0] = name[0];
    rest_name[1] = '.';
    rest_name[2] = ' ';
    j = 3;
    for(int i = 3; i < last_space_idx; ++i)
    {
        if(name[i] == ' ')
        {
            rest_name[j++] = name[i + 1];
            rest_name[j++] = '.';
            rest_name[j++] = ' ';
        }
    }
    rest_name[j - 1] = '\0';
    //printf("|%s|\n", rest_name);
    printf("%s, %s\n", last_name, rest_name);
}

int main() {
    char name[LEN];
    printf("Type a full name : ");
    fgets(name, LEN, stdin);
    printf("\n");
    name_abbreviated(name);
    return 0;
}

输出:

Type a full name : 
Davis, E. C. C.

或者,如果您愿意,请参阅 Live demo .

关于c - 如何在 C 中缩写全名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570121/

相关文章:

arrays - 返回 Hive 中数组中项目的索引

c - 如何获取指定架构(x86、pic Controller )中的芯片名称和可寻址内存?

c - 获取 argv[0] 中 n 和 argv 长度之间的子字符串

ruby - 如何在ruby中获取字符串数组的总和

c - 如何使用递归打印出 C 中一系列数字的所有排列?

c# - 在 C# 中设置的 2 个单词字符串中拆分字符串

c - 段错误追加空字符串 C

java - Spring批量写入固定格式文件

c - 外部、内部且没有链接,或者为什么这不起作用?

c - 为什么标准禁止将 sizeof 应用于函数