[英]Reading a substring with spaces from a line in C
我有一個帶頭信息的ASCII文件。 標頭中的其中一行如下所示:
# John Q. Public et al. 2014, to be submitted
我正在嘗試取這個名字。 這是我的代碼:
sscanf(line,"# %s et al.",NAME);
不幸的是,它僅獲得名字。 注意:名稱可以是1個或多個用空格分隔的令牌。 基本上,我需要獲得介於第一個哈希標記和“等”之間的所有內容。 轉換為單個字符串(char *)變量。
有什么建議么? 謝謝。
萬一您需要本機的東西:
bool readName(const char *line, char *name, int bufferSize)
{
const char *hash = strstr(line, "# ");
if(!hash)
return false;
const char *etal = strstr(hash+2, " et al.");
if(!etal)
return false;
size_t numChars = min(etal-hash-2, bufferSize-1);
strncpy(name, hash+2, numChars);
name[numChars] = '\0';
return true;
}
我會按照@pgm的建議將行讀入內存,然后使用正則表達式提取名稱。 在不了解您使用的平台/庫的情況下,我無法給出具體示例。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void between(const char *str, const char *key1, const char *key2, char *out){
char *from, *to, *p;
*out = '\0';
from = strstr(str, key1);
if(!from) return ;
from += strlen(key1);
to = strstr(from, key2);
if(!to) return ;//or rest ?
while(isspace(*from))
++from;
while(isspace(*--to))
;
for(p = from; p <= to; )
*out++ = *p++;
*out = '\0';
}
int main(){
char line[] = "# John Q. Public et al. 2014, to be submitted";
char NAME[32];
between(line, "#", "et al.", NAME);
printf("<%s>\n", NAME);//<John Q. Public>
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.