Example of replace() function in Kotlin

Learn about the replace() function in Kotlin, and demonstrate the example of the replace() function.
Submitted by IncludeHelp, on March 25, 2022

replace() Function

The replace() function returns a new string with all occurrences of oldChar (string to be replaced) replaced with newChar (string to replace with).


fun String.replace(
    oldChar: Char,
    newChar: Char,
    ignoreCase: Boolean = false
): String

Kotlin program to demonstrate the example of replace() function

// Example of replace() function
fun main()
	// Demonstrating the replace() function
	val pattern = Regex("Hi")

	// Replace all "Hi" with "Hello"
	println(pattern.replace("Hi, there.", "Hello"))
	println(pattern.replace("Hi Alex! Please say Hi to Boss.", "Hello"))
	println(pattern.replace("IncludeHelp", "Okay"))


Hello, there.
Hello Alex! Please say Hello to Boss.

Kotlin Regular Expression (Regex) Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.