gpt4 book ai didi

c - 在 C 中操作字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:01:52 25 4
gpt4 key购买 nike

我有一个包含很多电子邮件的文本文件,每封电子邮件的开头是 3 行标题信息,包括发件人:、主题:、日期:。我知道在每个 ctrl-L 字符之后是标题行,因此是 c==12 行。

目前我从数组中获取 1 行文本,例如:

From: Rollen Awen <reaw@yahoo.com>

From: muller@ngc.csc.ncsu.spu

所以现在我正在尝试使用分隔符来仅保留电子邮件地址,但我不确定如何去做。我必须能够处理任何类型的情况,无论是包含在 < > 中还是包含在 2 个空格之间。

例如,我想改变

From: Rollen Awen <reaw@yahoo.com>字符串只变成reaw@yahoo.com

或改变

From: muller@ngc.csc.ncsu.spu进入muller@ngc.csc.ncsu.spu

...
FILE *emaildata = fopen (argv[1], "r");

while((c=fgetc(emaildata))!=EOF){
if(c==12){
numberemails++;
fgets(nothing, sizeof(nothing), emaildata);
fgets(from, sizeof(from), emaildata);
fgets(subject, sizeof(subject), emaildata);
fgets(date, sizeof(date), emaildata);
//printf("%s", from);
}
...

最佳答案

这需要 memrchr() 如果您 #define _GNU_SOURCE glibc 会为您提供。如果您没有该功能,我相信您可以找到类似的功能或自己编写。

// input is either like "John Smith <jsmith@example.com>" or "jsmith@example.com"
// leading and trailing whitespace is skipped
// email is an out-param, must be an array at least as long as input
void parse_email_address(const char* input, char* email)
{
// skip leading whitespace
while (isspace(*input)) {
++input;
}

size_t len = strlen(input);

// ignore trailing whitespace
while (len > 0 && isspace(input[len - 1])) {
--len;
}

// parse friendly addresses like "John Smith <jsmith@example.com>"
// '>' must come last, and '<' must come before it
if (len > 0 && input[len - 1] == '>') {
const char* left = memrchr(input, '<', len);
if (left) {
len -= left - input + 2; // 2 for '<' and '>'
input = left + 1;
}
}

memcpy(email, input, len);
email[len] = '\0';
}

关于c - 在 C 中操作字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26395361/

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