1 Star 0 Fork 1

Chobits/C Code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
soundex_encoding.c 2.19 KB
一键复制 编辑 原始数据 按行查看 历史
Chobits 提交于 2023-03-16 19:32 . refine [rst].c code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1024
void append(char* buffer, char c)
{
for (int i = 0; i < MAX_LEN - 1; i++)
{
if (buffer[i] == '\0')
{
buffer[i] = c;
buffer[i + 1] = '\0';
return;
}
}
}
char* soundex_encoding(const char* s)
{
const char MAP[] = {
// A B C D E F G H I J K L M
'0', '1', '2', '3', '0', '1', '2', '0', '0', '2', '2', '4', '5',
// N O P Q R S T U V W X Y Z
'5', '0', '1', '2', '6', '2', '3', '0', '1', '0', '2', '0', '2'};
char* str = malloc(sizeof(MAX_LEN * (sizeof(char))));
strcpy(str, s);
str = strupr(str);
char buffer[MAX_LEN];
for (int i = 0; i < MAX_LEN; i++)
{
buffer[i] = '\0';
}
char prev = '?', prev_output = '?'; // 符号字符
// 沿用首字符
append(buffer, str[0]);
for (int i = 1; i < strlen(str) && strlen(buffer) < 4; i++)
{
char c = str[i];
// 判断字母是否为大写,且是否为符号字符
if (c >= 'A' && c <= 'Z' && c != prev)
{
prev = c;
char m = MAP[c - 'A'];
// 去除重复的字母
if (m != '0' && m != prev_output)
{
append(buffer, m);
prev_output = m;
}
}
}
if (buffer[1] == MAP[str[0] - 'A'])
{
for (int i = 1; i < MAX_LEN - 1; i++)
{
buffer[i] = buffer[i + 1];
}
}
free(str);
// 如果长度不够4就添加0
for (int i = strlen(buffer); i < 4; i++)
{
append(buffer, '0');
}
char* result = malloc(sizeof(MAX_LEN * (sizeof(char))));
strcpy(result, buffer);
return result;
}
int main(void)
{
char* s[] = {"Marc", "Earc", "Taylor", "Tttaylor", "Taaaaaylor", "ChenQingyu", "ChanQingyu!!"};
for (int i = 0; i < sizeof(s) / sizeof(s[0]); i++)
{
printf("%s\n", s[i]);
printf("%s\n", soundex_encoding(s[i]));
printf("\n");
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ChobitsY/C-Code.git
git@gitee.com:ChobitsY/C-Code.git
ChobitsY
C-Code
C Code
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385