Home > Software engineering >  How to get the count of specific letters in a String? (Android)
How to get the count of specific letters in a String? (Android)

Time:08-24

I need to count the number of times a letter's present in a String.

For example:

str = "/data/name/data/name"

How do we get the number of / in this string?

CodePudding user response:

val count = str.count { it == '/' }

CodePudding user response:

I think you can count with this way,

val str = "/data/name/data/name"
var count = 0
str.forEach {
   if(it == '/'){
       count  
   }
}

CodePudding user response:

To be honest, I am not sure whether you need an answer in java or kotlin (your tags include both), so if you need an answer in java:

String input = "/data/name/data/name";
char search = '/'; 
long count = input.chars().filter(ch -> ch == search).count();

(and if you need a kotlin version, just take a look at @Ivo's answer)

  • Related