String matching: Difference between revisions

→‎{{header|Kotlin}}: updated kotlin to find ALL occurrences of the string
(add sed)
(→‎{{header|Kotlin}}: updated kotlin to find ALL occurrences of the string)
Line 2,640:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scalakotlin">// version 1.0.6
fun main() {
 
fun main(args: Array<String>) {
val s1 = "abracadabra"
val s2 = "abra"
println("$s1 begins with $s2 : ${s1.startsWith(s2)}")
println("$s1 ends with $s2 : ${s1.endsWith(s2)}")
val b = s2 in s1
if (b) {
print("$s1 contains $s2 at these indices: $b")
if (b) println(" at locations ${s1.indexOf(s2) + 1} and ${s1.lastIndexOf(s2) + 1}")
// can use indexOf to get first index or lastIndexOf to get last index
else println()
// to get ALL indices, use a for loop or Regex
else println()
s2.toRegex(RegexOption.LITERAL).findAll(s1).joinToString { it.range.start.toString() }
)
}
else println("$s1 does not contain $2.")
}</syntaxhighlight>
 
{{out}}
<pre>
abracadabra begins with abra : true
abracadabra ends with abra : true
abracadabra contains abra at these indices: true at locations 1 and0, 87
</pre>
 
32

edits