如何從其含義中拆分該詞 1.猛犸象:大
我的代碼:
void ReadFromFile(){
FILE *dictionary = fopen("dictionary.txt", "r");
char word[20];
char meaning[50];
while(fscanf(dictionary, "%[^:]:%[^\t]\t", word, meaning) == 2){
printf("%s %s\n", word, meaning);
}
fclose(dictionary);
uj5u.com熱心網友回復:
假設word和meaning不包含數字和點,我的方法如下:
- 首先,將數字和點上的輸入行拆分為形式為 的標記
word: meaning。 - 接下來用冒號字符分隔每個標記。
- 最后,洗掉前導和尾隨的空白字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INFILE "dictionary.txt"
void split(char *str);
void separate(char *str);
char *trim(char *str);
/*
* split line on serial number into "word" and "meaning" pairs
* WARNING: the array of "str" is modified
*/
void
split(char *str)
{
char *tk; // pointer to each token
char delim[] = "0123456789."; // characters used in the serial number
tk = strtok(str, delim); // get the first token
while (tk != NULL) {
separate(tk); // separate each token
tk = strtok(NULL, delim); // get the next token
}
}
/*
* separate the pair into "word" and "meaning" and print them
*/
void
separate(char *str)
{
char *p;
if (NULL == (p = index(str, ':'))) {
// search a colon character in "str"
fprintf(stderr, "Illegal format: %s\n", str);
exit(1);
}
*p = '\0'; // terminate the "word" string
// now "p" points to the start of "meaning"
printf("%s %s\n", trim(str), trim(p));
}
/*
* remove leading and trailing whitespaces
* WARNING: the array of "str" is modified
*/
char *
trim(char *str)
{
char *p;
for (p = str; *p != '\0'; p ); // jump to the end of "str"
for (; p > str && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n' || *p == '\0'); p--);
// rewind the pointer skipping blanks
* p = '\0'; // chop the trailing blanks off
for (p = str; *p != '\0' && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n'); p );
// skip leading blanks
return p;
}
int
main()
{
FILE *fp;
char str[BUFSIZ];
if (NULL == (fp = fopen(INFILE, "r"))) {
perror(INFILE);
exit(1);
}
while (NULL != fgets(str, BUFSIZ, fp)) {
split(trim(str));
}
fclose(fp);
return 0;
}
輸出:
foe enemy
vast huge
purchase buy
drowsy sleepy
absent missing
prank trick
[snip]
[替代]
我想C可能不適合這種字串操作的語言。高級語言,例如python,perl或ruby將用更少的代碼解決它。這是一個python將產生相同結果的示例:
import re
with open("dictionary.txt") as f:
s = f.read()
for m in re.finditer(r'\d \.\s*(. ?):\s*(\S )', s):
print(m.group(1) " " m.group(2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/347894.html
上一篇:使用bash-c逐行決議
