×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String replace() Method

By IncludeHelp Last updated : October 22, 2024

Description and Usage

The replace() method replaces a character from the given string with a new character.

Syntax

string_Name.replace(char stringChar, char newChar)

Parameters

The method accepts two parameters,

  1. The character to be replaced in the string.
  2. The character which is placed in place of the old character.

Return Value

It returns a string which contains the replaced character.

Example 1: Replacing character with single occurrence in the string

object MyClass {
    def main(args: Array[String]) {
        val myString = "scala programming language"
        println("The string is '" + myString + "'")
        
        val newString = myString.replace('s', 'S')
        println("The string after replacing the characters is " + newString)
    }
}

Output

The string is 'scala programming language'
The string after replacing the characters is Scala programming language

Example 2: Replacing character with multiple occurrences in the string

object MyClass {
    def main(args: Array[String]) {
        val myString = "scala programming language"
        println("The string is '" + myString + "'")
        
        val newString = myString.replace('a', 'A')
        println("The string after replacing the characters is " + newString)
    }
}

Output

The string is 'scala programming language'
The string after replacing the characters is scAlA progrAmming lAnguAge

Example 3: Trying to replace character not present in the string

object MyClass {
    def main(args: Array[String]) {
        val myString = "scala programming language"
        println("The string is '" + myString + "'")
        
        val newString = myString.replace('z', 'Z')
        println("The string after replacing the characters is " + newString)
    }
}

Output

The string is 'scala programming language'
The string after replacing the characters is scala programming language

In the above code, the string remains as it is there is a match for the given character so nothing is replaced.

Comments and Discussions!

Load comments ↻





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