Fundamentals 14 min read

Scala String Basics: Creation, Manipulation, and Common Methods

This tutorial explains how Scala treats strings as immutable Java objects, shows how to create and modify strings using literals, explicit types, and StringBuilder, demonstrates length retrieval, concatenation, formatted output, and provides a comprehensive list of java.lang.String methods usable in Scala.

Big Data Technology & Architecture
Big Data Technology & Architecture
Big Data Technology & Architecture
Scala String Basics: Creation, Manipulation, and Common Methods

In Scala, a String is a Java java.lang.String object and is immutable; any modification creates a new string instance, while mutable objects such as arrays can be changed.

String literals can be assigned directly or with an explicit type, and the compiler can infer the type automatically. Example:

object Test {
    val greeting: String = "Hello,World!"
    def main(args: Array[String]) {
        println(greeting)
    }
}

Running the program prints Hello, world!. For mutable strings, StringBuilder can be used:

object Test {
    def main(args: Array[String]) {
        val buf = new StringBuilder
        buf += 'a'
        buf ++= "bcdef"
        println("buf is : " + buf.toString)
    }
}

The length of a string is obtained with the length() method:

object Test {
    def main(args: Array[String]) {
        val palindrome = "www.runoob.com"
        val len = palindrome.length()
        println("String Length is : " + len)
    }
}

String concatenation can be performed with the concat() method or the + operator:

val combined = str1.concat(str2)
// or
val combined = str1 + str2

Formatted output can be produced with printf() (which prints directly) or String.format() (which returns a formatted string):

val fs = printf("float %f, int %d, string %s", floatVar, intVar, stringVar)
println(fs)

The table below lists common java.lang.String methods that are available in Scala, including character access, comparison, concatenation, searching, replacement, splitting, case conversion, trimming, and more.

Number

Method and Description

1

char charAt(int index)

– Returns the character at the specified index.

2

int compareTo(Object o)

– Compares the string with an object.

3

int compareTo(String anotherString)

– Lexicographically compares two strings.

4

int compareToIgnoreCase(String str)

– Lexicographically compares two strings, ignoring case.

5

String concat(String str)

– Concatenates the specified string to the end of this string.

6

boolean contentEquals(StringBuffer sb)

– Compares this string to the specified StringBuffer.

7

static String copyValueOf(char[] data)

– Returns a string representing the character array.

8

static String copyValueOf(char[] data, int offset, int count)

– Returns a string representing a subarray of characters.

9

boolean endsWith(String suffix)

– Tests whether the string ends with the specified suffix.

10

boolean equals(Object anObject)

– Compares this string to the specified object.

11

boolean equalsIgnoreCase(String anotherString)

– Compares this string to another, ignoring case.

12

byte[] getBytes()

– Encodes this string into a byte array using the platform's default charset.

13

byte[] getBytes(String charsetName)

– Encodes this string into a byte array using the specified charset.

14

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

– Copies characters from this string into the destination array.

15

int hashCode()

– Returns a hash code for this string.

16

int indexOf(int ch)

– Returns the index of the first occurrence of the specified character.

17

int indexOf(int ch, int fromIndex)

– Returns the index of the first occurrence of the character, starting at the given index.

18

int indexOf(String str)

– Returns the index of the first occurrence of the specified substring.

19

int indexOf(String str, int fromIndex)

– Returns the index of the first occurrence of the substring, starting at the given index.

20

String intern()

– Returns a canonical representation for the string object.

21

int lastIndexOf(int ch)

– Returns the index of the last occurrence of the specified character.

22

int lastIndexOf(int ch, int fromIndex)

– Returns the index of the last occurrence of the character, searching backward from the given index.

23

int lastIndexOf(String str)

– Returns the index of the last occurrence of the specified substring.

24

int lastIndexOf(String str, int fromIndex)

– Returns the index of the last occurrence of the substring, searching backward from the given index.

25

int length()

– Returns the length of the string.

26

boolean matches(String regex)

– Tells whether this string matches the given regular expression.

27

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

– Tests if two string regions are equal.

28

boolean regionMatches(int toffset, String other, int ooffset, int len)

– Tests if two string regions are equal.

29

String replace(char oldChar, char newChar)

– Returns a new string resulting from replacing all occurrences of oldChar with newChar.

30

String replaceAll(String regex, String replacement)

– Replaces each substring that matches the given regular expression with the given replacement.

31

String replaceFirst(String regex, String replacement)

– Replaces the first substring that matches the given regular expression with the given replacement.

32

String[] split(String regex)

– Splits this string around matches of the given regular expression.

33

String[] split(String regex, int limit)

– Splits this string around matches of the given regular expression, with a limit on the number of resulting substrings.

34

boolean startsWith(String prefix)

– Tests if this string starts with the specified prefix.

35

boolean startsWith(String prefix, int toffset)

– Tests if the substring starting at the specified offset starts with the given prefix.

36

CharSequence subSequence(int beginIndex, int endIndex)

– Returns a new character sequence that is a subsequence of this sequence.

37

String substring(int beginIndex)

– Returns a new string that is a substring of this string.

38

String substring(int beginIndex, int endIndex)

– Returns a new string that is a substring of this string.

39

char[] toCharArray()

– Converts this string to a new character array.

40

String toLowerCase()

– Converts all characters in this string to lower case using the default locale.

41

String toLowerCase(Locale locale)

– Converts all characters in this string to lower case using the specified locale.

42

String toString()

– Returns this string itself.

43

String toUpperCase()

– Converts all characters in this string to upper case using the default locale.

44

String toUpperCase(Locale locale)

– Converts all characters in this string to upper case using the specified locale.

45

String trim()

– Removes leading and trailing whitespace from this string.

46

static String valueOf(primitive data type x)

– Returns the string representation of the given primitive value.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingStringTutorialScalaImmutablestringbuilder
Big Data Technology & Architecture
Written by

Big Data Technology & Architecture

Wang Zhiwu, a big data expert, dedicated to sharing big data technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.