计算 C 中 txt 文件中字符串出现的次数(0-9)
计算 C 中 txt 文件中字符串中出现的次数(0-9)
我创建了从文件中读取字符串并将其保存为变量“line”的部分
我的想法是创建一个包含 10 个元素的表开头是 0,例如,如果我发现 2 个 0 的数字,它会更改 2 中的 table[1],或者如果找到 1 个 9 的数字,它将 table[10] 更改为 1,但无法实现它
字符串的输出“456 890 111111”应该是:
数字 1 出现 6 次
数字 1 出现 1 次
...
#include <stdio.h>
#include <stdlib.h>
int main()
{
char line[255];
int table[10];
FILE *f = fopen("input.txt", "r");
fgets(line, 255, f);
printf("String read: %s\n", line);
fclose(f);
return 0;
}
更新的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char line[255];
unsigned int table[10] = { 0 };
FILE *f = fopen("input.txt", "r");
fgets(line, 255, f);
printf("String read: %s\n", line);
int n=0;
for ( char *p = line; *p != '\0'; p++ )
{
if ( '0' <= *p && *p <= '9' ) {
++table[*p - '0'];
}
}
fclose(f);
for (int i=0; table[i] < 10; i++) {
printf("Number", i, "apears", table[i], "times");
}
return 0;
}
Count number (0-9) occurrences in a string from a txt file in C
I created the part that reads the string from the file and saves it as the variable "line"
My idea is to create a table with 10 elements that at the beginning are 0 and for example if I found 2 numbers of 0 it changes the table[1] in 2 or if it founds 1 number of 9 it changes table[10] to 1 but couldn't implement it
Output of the string "456 890 111111" should be:
Number 1 appears 6 times
Number 1 appears 1 times
...
#include <stdio.h>
#include <stdlib.h>
int main()
{
char line[255];
int table[10];
FILE *f = fopen("input.txt", "r");
fgets(line, 255, f);
printf("String read: %s\n", line);
fclose(f);
return 0;
}
Updated code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char line[255];
unsigned int table[10] = { 0 };
FILE *f = fopen("input.txt", "r");
fgets(line, 255, f);
printf("String read: %s\n", line);
int n=0;
for ( char *p = line; *p != '\0'; p++ )
{
if ( '0' <= *p && *p <= '9' ) {
++table[*p - '0'];
}
}
fclose(f);
for (int i=0; table[i] < 10; i++) {
printf("Number", i, "apears", table[i], "times");
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于数字的计数不能为负数,因此最好使用元素类型 unsigned int 来声明数组。您还需要用零初始化数组。
例如
,在循环中时,您可以计算字符串中的数字。例如,
所有数字作为字符都按顺序表示,没有其他中间符号。
请注意数组中的索引从 0 开始。
更新问题中的代码后,此 for 循环
是不正确的。对于初学者来说,这个条件
table[i] < 10 毫无意义。并阅读有关 printf 的文档。
至少循环应该看起来像
As the count of a digit can not be negative it is better to declare the array with the element type unsigned int. Also you need to initialize the array with zeroes.
For example
when in a loop you can count digits in the string. For example
All digits as characters are represented sequentially without other intermediate symbols.
Pay attention to that indices in arrays start from 0.
After you updated the code in the question then this for loop
is incorrect. For starters this condition
table[i] < 10
makes no sense. And read the documentation aboutprintf
.At least the loop should look like