c语言如何从一个文本中筛选出特定字符串
如图,为了将txt文件每行字符串包含的数字提取出来,编写了一个程序。
思路:
找到is,然后指针后移三位,然后到达空格,则停止。再将字符转换为数字。
具体操作:
首先用fget()读取每行,然后用strstr()找到is,然后指针后移三位,再判断空格,复制保存。最后将提取出来的数字字符串转换成整型
源码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69#include <stdio.h> #include <iostream> int main(void) { FILE *input_file; unsigned int file_size = 0; //读取文件的字节数 char line[64]; //接收文件每行 char result[300][64] = {0}; //二维数组,存放结果字符串 int result_final[300] = { 0 }; //数组,存放结果字符串 int i = 0;//最终检测出的多少个数字 int len = 0; int len1 = 0; int a = 0; int b = 1; input_file = fopen("test.txt", "rb+"); if (input_file == NULL) { printf("can not find file!n"); exit(0); } else { printf("File opened successful!n"); } while (fgets(line, sizeof(line), input_file)) { //用fgets函数逐行读取到line char *pLast = strstr(line, "is"); //用strrchr查找'='字符最后出现的位置, if (NULL != pLast) { pLast = pLast + 3; //is后面三位是数字开头 while (*pLast != ' ') { len++; pLast++; } memcpy(result[i], pLast- len, len);//将每行最后一个"is"之后的字符赋给result len=0; i++; } } fclose(input_file); //将提取出来的数字字符串转换成整型 for (int j = 0; j <i ; j++) { printf("result[%d]=%st", j,result[j]); len1 = strlen(result[j]); a = 0; b = 1; int temp = 0; while (a < len1) { //b = b * 10; temp= (result[j][len1-1-a]-'0')*b +temp; b = b * 10; a++; } result_final[j] = temp; printf("result[%d]=%dn", j, result_final[j]); } return 0; }
最后
以上就是细腻百合最近收集整理的关于C语言定位并抓取文件中的特定字符串思路:具体操作:源码的全部内容,更多相关C语言定位并抓取文件中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复