An example of how to count the number of characters in a file using kotlin
preface
For developers, counting the number of characters in a file is a common program. Today, use the kotlin you just learned to realize it. I won't say much now. Let's take a look at the detailed introduction.
The method is as follows:
First, find a file to count.
Then establish a HashMap to store the statistical results.
Read the file content and convert it into char for traversal statistics
Readtext() reads the contents of the file
Tochararray() to char array
Filternot (char:: iswhitespace) ignores spaces
During traversal, the currently traversed map [it] is assigned to count. If this character is not found in the map, that is, count = = null, it is the first record, and map [it] is 1. Otherwise, map [it] has been recorded, and 1 is added to the original count.
Finally, the statistical results are output
The implementation effect is as follows
The above reading is not concise enough. We can simplify it a little more. There is no need to declare HashMap at all.
Can achieve the same effect. This is functional programming.
Attached: HashMap structure diagram
summary
The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.