Skip to main content

How to replace a specific character or substring in a string in Kotlin

How to replace a specific character or substring in a string in Kotlin.

Here's a step-by-step tutorial on how to replace a specific character or substring in a string in Kotlin.

Step 1: Create a String

First, let's start by creating a string that we want to modify. We can assign it to a variable using the val keyword:

val originalString = "Hello World!"

In this example, our original string is "Hello World!".

Step 2: Replace Single Character

If you want to replace a single character in the string, you can use the replace function. This function takes two parameters - the old character and the new character you want to replace it with. Here's an example:

val modifiedString = originalString.replace('o', 'x')

In this example, we replace all occurrences of the character 'o' with 'x'. The resulting modified string will be "Hellx Wxrld!".

Step 3: Replace Substring

To replace a substring within a string, you can use the replace function as well. This time, you pass in the old substring and the new substring you want to replace it with. Here's an example:

val modifiedString = originalString.replace("World", "Universe")

In this example, we replace the substring "World" with "Universe". The resulting modified string will be "Hello Universe!".

Step 4: Regular Expression Replacement

You can also use regular expressions to replace characters or substrings in a string. The replace function can accept a regular expression as the first parameter. Here's an example:

val modifiedString = originalString.replace(Regex("[aeiou]"), "*")

In this example, we replace all vowels (a, e, i, o, u) with an asterisk (). The resulting modified string will be "Hll Wrld!".

Step 5: Case Insensitive Replacement

By default, the replace function is case-sensitive. If you want to perform a case-insensitive replacement, you can use the RegexOption.IGNORE_CASE option. Here's an example:

val modifiedString = originalString.replace(Regex("hello", RegexOption.IGNORE_CASE), "Hi")

In this example, we replace the substring "hello" with "Hi", regardless of the letter case. The resulting modified string will be "Hi World!".

That's it! You now know how to replace a specific character or substring in a string in Kotlin.