Home > Net >  How can I check whether a given string contains another substring more than once?
How can I check whether a given string contains another substring more than once?

Time:06-27

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; 
 }

CodePudding user response:

Are you sure that your code, albeit a bit redundant, doesn't work?

The following should do what you seemingly want it to, but is a bit cleaner :)

fun isFieldRepeated(jsonIn: String, field:String): Boolean { 
    val index: Int =jsonIn.indexOf(field)
    return index!=-1 && jsonIn.indexOf(index, field)!=-1
}

Hope it helps!

CodePudding user response:

I would simplify it to

fun isFieldRepeated(jsonIn: String, field:String): Boolean =
  jsonIn.firstIndexOf(field) != jsonIn.lastIndexOf(field)

CodePudding user response:

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"))
  • Related