C
C
Cyber ​​Cyber2021-09-11 12:21:57
Rust
Cyber ​​Cyber, 2021-09-11 12:21:57

How to count the number of certain characters in a string in Rust?

For example, I have a string of 0's and 1's, how can I find out how many 1's there are in it? I wanted to break a string into iterators, but there is no implementation of an iterator for strings, maybe there is some kind of count() that takes an argument like a closure? I'm studying the language recently, I'm not yet completely familiar with the standard library, well, or I didn't search well.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Lesnikov, 2021-09-11
​​@KiberCuber

There is an important nuance in the formulation of the problem: what should be considered a symbol?
If we consider the usual built-in char, then we simply get an .chars()iterator from the string, filter and count: But we must understand that on strings with grapheme clusters (namely, they are usually considered by ordinary users as characters ), such code will work crookedly. If this is important to us, then we go for lib.rs/unicode_segmentation and use its method:
"12121".chars().filter(|&c| c == '2').count()

"éaébé".graphemes(true).filter(|&g| g == "é").count()

Sandbox .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question