计算机统计字符数,计算文件流中的字符数(Counting characters in a file stream)

I'm trying to make a function how_many(), which counts the number of characters of a certain type, say "\n" or ",", in a file stream. Here is my (failed) attempt:

int how_many(char mychar, anifstream myfile){

int result;

while(!myfile.eof())

{

if(myfile.get()==mychar){result=result+1;}

}

myfile.close(); // Closes the filestream "my file"

return result;

}

First question: is "\n" a character or a string? (If so, then I should make the first input a string instead of a character)

Second question: can you explain the resulting error message? (or alternatively, directly point out the misuse of syntax in my code):

warning: result of comparison against a string literal is unspecified

(use strncmp instead) [-Wstring-compare]

note: candidate function not viable: no known conversion from 'const char [2]' to

'char' for 1st argument

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设要统计的字列表为{1, 2, 3, 4, 4, 3, 2, 5, 6, 6, 7, 7, 8},可以使用Java 8中的stream流和collectors工具类来实现: ``` import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class UniqueNumberCounter { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 3, 2, 5, 6, 6, 7, 7, 8); Map<Integer, Long> counts = numbers.stream() .collect(Collectors.groupingBy(e -> e, Collectors.counting())); System.out.println("Numbers that appear once:"); counts.entrySet().stream() .filter(e -> e.getValue() == 1) .map(Map.Entry::getKey) .forEach(System.out::println); } } ``` 运行结果为: ``` Numbers that appear once: 1 5 8 ``` 解释一下代码: 1. 首先将字列表转换为一个流对象,使用groupingBy方法将相同字分为一组,然后使用counting方法统计每组中字出现的次,最终得到一个Map<Integer, Long>类型的对象,其中key表示字,value表示出现次。 ``` Map<Integer, Long> counts = numbers.stream() .collect(Collectors.groupingBy(e -> e, Collectors.counting())); ``` 2. 使用entrySet方法将Map对象转换为一个Set集合,然后通过stream方法将其转换为一个流对象。使用filter方法过滤出现次为1的字,map方法将Map.Entry对象转换为字,最后使用forEach方法遍历输出。 ``` counts.entrySet().stream() .filter(e -> e.getValue() == 1) .map(Map.Entry::getKey) .forEach(System.out::println); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值