C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Scala program that uses capitalize on string
// This is a string.
val name = "plutarch"
// Use the capitalize function to uppercase the first letter.
val cap = name.capitalize
println(cap)
Output
Plutarch
Loops: We can use the for-loop to access all the strings returned by lines. The foreach function and a lambda expression also works.
DefScala program that uses lines
val data = "cat\nbird\nfish and dog"
// Loop over lines and print them.
for (line <- data.lines) {
println(line)
}
println()
// Use foreach and a lambda expression to print lines.
data.lines.foreach(println(_))
Output
cat
bird
fish and dog
cat
bird
fish and dog
Tip: With these functions, only letters are changed. A space is left alone. And already uppercased or lowercased letters are also ignored.
Scala program that uses toUpperCase, toLowerCase
val name = "don quixote"
// Uppercase all letters in the string.
// ... The space is left unchanged.
val upper = name.toUpperCase()
println(upper)
// Lowercase the letters.
val lower = upper.toLowerCase()
println(lower)
Output
DON QUIXOTE
don quixote
Scala program that multiplies string
// Multiply this string (concatenate it repeatedly).
val letters = "abc" * 3
println(letters)
// Create a string of nine hyphens.
val separator = "-" * 9
println(separator)
Output
abcabcabc
---------
Result: The characters in the resulting string are in reverse order. No custom function was needed to reverse a string.
Scala program that uses reverse, IndexedSeqOptimized
val id = "x100"
// Use reverse from scala.collection.IndexedSeqOptimized.
val result = id.reverse
// The characters in the string are now reversed.
println(id)
println(result)
Output
x100
001x
Test: This method sees if the left and right parts are combined to equal the "combined" strings.
Result: The string "abcd" is combined from "ab" and "cd." The strings' characters are tested.
Scala program that uses equals operator
def test(combined: String, left: String, right: String) = {
// The equals operator tests the String's data.
// ... It compares characters.
if (combined == left + right) {
println(combined, true)
} else {
println(combined, false)
}
}
// These print true.
test("abcd", "ab", "cd")
test("catdog", "cat", "dog")
// This prints false.
test("xxyy", "ef", "gh")
Output
(abcd,true)
(catdog,true)
(xxyy,false)