C语言编写从整型数组中检索给定数值的函数

《从语言程序设计教程(朱鸣华)第3版》第8章145页编程题3

原题:编写试从整型数组中检索给定数值的函数,若找到则输出该数值在数组中的位置

代码如下

#define _CRT_SECURE_NO_WARNINGS 1
/*编写从整型数组中检索给定数值的函数,
若找到则输出该数值在数组中的位置*/
#include<stdio.h>
int main()
{
   
	int i, j, k;
	int array1[9] =
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以按照以下步骤实现: 1. 打开文本文件并读取其中的内容。 2. 定义一个函数,用于统计给定单词在文本中出现的总次数。在函数中,可以使用字符串处理函数 strtok() 将文本分割成单词,然后逐一比较每个单词是否与给定单词相同,若相同则累加计数器。 3. 定义另一个函数,用于检索输出某个单词出现在文本中的行号、在该行中出现的次数以及位置。在函数中,可以使用字符串处理函数 strstr() 在每一行中查找给定单词,若找到则输出行号、出现次数以及位置。 4. 关闭文件并结束程序。 下面是一份简单的实现代码,仅供参考: ```c #include <stdio.h> #include <string.h> #define MAX_LINE_LEN 1024 // 最大行长 #define MAX_WORD_LEN 64 // 最大单词长 // 统计给定单词在文本中出现的总次数 int count_word(const char* filename, const char* word) { FILE* fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); return -1; } char line[MAX_LINE_LEN]; int count = 0; while (fgets(line, MAX_LINE_LEN, fp)) { char* token = strtok(line, " \t\n\r"); // 分割单词 while (token) { if (strcmp(token, word) == 0) { count++; } token = strtok(NULL, " \t\n\r"); } } fclose(fp); return count; } // 检索输出某个单词出现在文本中的行号、在该行中出现的次数以及位置 void search_word(const char* filename, const char* word) { FILE* fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); return; } char line[MAX_LINE_LEN]; int line_num = 1; while (fgets(line, MAX_LINE_LEN, fp)) { char* pos = line; int count = 0; while ((pos = strstr(pos, word))) { // 查找单词 count++; printf("Line %d, count %d, position %ld\n", line_num, count, pos - line + 1); pos += strlen(word); } line_num++; } fclose(fp); } int main() { const char* filename = "test.txt"; const char* word = "hello"; int count = count_word(filename, word); if (count >= 0) { printf("%s appears %d times in %s\n", word, count, filename); } search_word(filename, word); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

离歌慢饮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值