String matching: Difference between revisions
Content added Content deleted
(add sed) |
(→{{header|Kotlin}}: updated kotlin to find ALL occurrences of the string) |
||
Line 2,640: | Line 2,640: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
<syntaxhighlight lang=" |
<syntaxhighlight lang="kotlin"> |
||
fun main() { |
|||
fun main(args: Array<String>) { |
|||
val s1 = "abracadabra" |
val s1 = "abracadabra" |
||
val s2 = "abra" |
val s2 = "abra" |
||
println("$s1 begins with $s2 |
println("$s1 begins with $s2: ${s1.startsWith(s2)}") |
||
println("$s1 ends with $s2 |
println("$s1 ends with $s2: ${s1.endsWith(s2)}") |
||
val b |
val b = s2 in s1 |
||
if (b) { |
|||
print("$s1 contains $s2 |
print("$s1 contains $s2 at these indices: ") |
||
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 |
|||
⚫ | |||
// to get ALL indices, use a for loop or Regex |
|||
⚫ | |||
s2.toRegex(RegexOption.LITERAL).findAll(s1).joinToString { it.range.start.toString() } |
|||
) |
|||
} |
|||
else println("$s1 does not contain $2.") |
|||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
abracadabra begins with abra |
abracadabra begins with abra: true |
||
abracadabra ends with abra |
abracadabra ends with abra: true |
||
abracadabra contains abra |
abracadabra contains abra at these indices: 0, 7 |
||
</pre> |
</pre> |
||