Skip to main content

Strings

This document explains different string funcitons in scala. The below list will cover few popular functions.

S. NoScala String FunctionDescription
1lengthReturns the length of the string.
2charAt(index: Int)Returns the character at the specified index in the string.
3substring(start: Int, end: Int)Extracts a substring from the given start index to the end index (exclusive).
4toUpperCaseConverts all characters in the string to uppercase.
5toLowerCaseConverts all characters in the string to lowercase.
6trimRemoves leading and trailing whitespaces from the string.
7split(delimiter: String)Splits the string into an array of substrings based on the given delimiter.
8startsWith(prefix: String)Checks if the string starts with the specified prefix.
9endsWith(suffix: String)Checks if the string ends with the specified suffix.
10indexOf(str: String)Returns the index of the first occurrence of the specified substring in the string.
11lastIndexOf(str: String)Returns the index of the last occurrence of the specified substring in the string.
12replace(oldStr: String, newStr: String)Replaces all occurrences of the old string with the new string.
13isEmptyChecks if the string is empty (contains no characters).
14nonEmptyChecks if the string is not empty (contains characters).
15concat(str: String)Concatenates the given string with the original string.
16stripPrefix(prefix: String)Removes the specified prefix from the beginning of the string.
17stripSuffix(suffix: String)Removes the specified suffix from the end of the string.
18replaceAll(regex: String, replacement: String)Replaces all substrings that match the given regular expression with the replacement string.
19matches(regex: String)Checks if the string matches the given regular expression.
20charAt(index: Int)Returns the character at the specified index in the string.
21isEmptyChecks if the string is empty (contains no characters).
22nonEmptyChecks if the string is not empty (contains characters).
23distinctReturns a new string with duplicate characters removed.
24reverseReverses the order of characters in the string.
25slice(start: Int, end: Int)Extracts a slice of characters from the given start index to the end index (exclusive).
26replaceAllLiterally(target: String, replacement: String)Replaces all occurrences of the target string with the replacement string. This function performs a literal replacement without using regular expressions.
27splitAt(index: Int)Splits the string into two parts at the specified index.
28contains(str: String)Checks if the string contains the specified substring.
29contentEquals(str: CharSequence)Checks if the string's content is equal to the specified CharSequence.
30matches(regex: Regex)Checks if the string matches the specified regular expression (Regex).
31compareTo(str: String)Compares the string lexicographically with another string.
32compareToIgnoreCase(str: String)Compares the string lexicographically, ignoring case, with another string.
33padTo(length: Int, elem: Char)Pads the string with the specified character to the given length.
34patch(start: Int, patch: String, replaced: Int)Replaces 'replaced' characters at the 'start' index with the 'patch' string.
35replaceFirst(regex: String, replacement: String)Replaces the first occurrence of the regex with the replacement string.
36replaceFirst(regex: Regex, replacement: String)Replaces the first occurrence of the regex with the replacement string.
37replaceSomeIn(target: CharSequence, replacer: String => Option[String])Replaces some occurrences of the target string based on a replacer function.
38matchesPattern(str: String)Checks if the string matches the pattern specified in a StringContext.
39stripLineEndRemoves any line ending characters (CR, LF) at the end of the string.
40linesIteratorReturns an iterator of lines from the string.
41format(args: Any*)Creates a formatted string using the specified arguments.
42getBytes(charset: String)Converts the string to an array of bytes using the specified charset.
43getChars(srcBegin: Int, srcEnd: Int, dest: Array[Char], destBegin: Int)Copies characters from this string to the destination character array.
44internReturns a canonical representation for the string.
45codePointAt(index: Int)Returns the Unicode code point at the specified index.
46codePointBefore(index: Int)Returns the Unicode code point before the specified index.
47codePointCount(beginIndex: Int, endIndex: Int)Returns the number of Unicode code points in the specified text range.
48offsetByCodePoints(index: Int, codePointOffset: Int)Returns the index within this string that is offset from the given index by codePointOffset code points.
49matchesLiteral(str: String)Checks if the string matches the specified literal.
50getBytesEncodes the string into a sequence of bytes using the platform's default charset.
51getBytes(charset: Charset)Encodes the string into a sequence of bytes using the specified charset.
52stripMarginStrips a margin from each line in the string.
53stripMargin(marginChar: Char)Strips a margin from each line in the string using the specified margin character.
54stripMargin(margin: String)Strips a margin from each line in the string using the specified margin string.
55isBlankChecks if the string is blank (empty or contains only whitespaces).
56linesSplits the string into a sequence of lines.
57charAt(index: Int)Returns the character at the specified index in the string.
58getBytesEncodes the string into a sequence of bytes using the platform's default charset.
59getBytes(charset: Charset)Encodes the string into a sequence of bytes using the specified charset.
60equalsIgnoreCase(str: String)Compares this string to another string, ignoring case considerations.
61contentEquals(sb: StringBuffer)Checks if the string's content is equal to the specified StringBuffer.
62contentEquals(sb: StringBuilder)Checks if the string's content is equal to the specified StringBuilder.
63internReturns a canonical representation for the string.
64linesIteratorReturns an iterator of lines from the string.
65compareToIgnoreCase(str: String)Compares the string lexicographically, ignoring case, with another string.

String interpolators

In scala there are few string interpolators that provides more flexibility in concating strings.

1. S-interpolator

Below example explains how string contatination possible using dynamic variables in middle

val name = "Foo"

val welcomeMessage = s"Hello $name, welcome to the site." // the $name would be replaced with value and creates final string

val age = 10

val info = s"Your age is ${age + 3}" // This will also works.

2. F-interpolator

Below exmaple explains how it works

    object InterpolatorsExample extends App {

val name = "Foo"
val zipCode = 500012
val salary = 25.323894f

val salrayMessage = f"Dear $name Your pay rate per hour is $salary%8.2f, your zip code is $zipCode%s"

println(salrayMessage)

}

String f interpolator

3. Raw interpolator

The raw interpolator ignores escape characters inside, observe below example

println(s"1. Dear customer \n Welcome") // Prints new line like
1. Dear customer
Welcome


println(raw"2. Dear customer \n Welcome") // Prints raw characters
2. Dear customer \n Welcome