Reputation:
How can I check whether a given string contains another substring more than once?
fun isFieldRepeated(jsonIn: String, field:String): Boolean {
var count: Int = 0;
while (jsonIn.indexOf(field) > -1) {
jsonIn = jsonIn.substring(jsonIn.indexOf(field)+field.length(),jsonIn.length());
count++;
}
if(count>1)
return true;
return false;
}
Upvotes: 1
Views: 379
Reputation: 7173
fun isFieldRepeated(jsonIn: String, field: String): Boolean {
return jsonIn.windowed(field.length) { it == field }.count { it } > 1
}
Or as an extension function:
fun String.isFieldRepeated(field: String) = windowed(field.length) { it == field }.count { it } > 1
... to be used for example like this:
println("abcdefghcdij".isFieldRepeated("cd"))
Upvotes: 0
Reputation: 1
I would simplify it to
fun isFieldRepeated(jsonIn: String, field:String): Boolean =
jsonIn.firstIndexOf(field) != jsonIn.lastIndexOf(field)
Upvotes: 1