Contenido del Curso
Introduction to Scala
Introduction to Scala
Commonly Used String Methods
Like with many other built-in data types and classes in Scala, you do not have to code some common operations with strings yourself. Instead, String
has a handful of quite useful methods which perform these operations.
Without further ado, let's discuss some of the most commonly used string methods.
Splitting a String
It is often the case when we want to split a certain string into certain chunks (e.g. words). Luckily, String
has a built-in method for that – the split()
method which splits a string into an array of substrings (returns an Array
) based on a specified delimiter.
Let's take a look at the following example to clarify this:
Main
object Main { def main(args: Array[String]): Unit = { val sentence = "Learning Scala is cool" val words = sentence.split(" ") for (word <- words) { println(word) } } }
Here, we split our sentence
based on the whitespace by passing " "
as the argument of the split()
method. This method has only one argument which must be of String
class, so you can use a sequence of characters as the delimiter.
Checking for Substring
In order to check if a string contains a specified substring (a certain part of the string), we can use the contains()
method which takes exactly one argument (the substring) which can be a String
or a Char
(it can be of other data types, but it makes little sense for strings). This method returns a boolean value, namely true
if the substring is indeed a part of our string, and false
otherwise.
Here is an example:
Main
object Main { def main(args: Array[String]): Unit = { val message = "Yo, boss, I have already completed this task." val isInformal = message.contains("Yo") if (isInformal) { println("The message is informal.") } else { println("The message is formal.") } } }
In our case, Yo
is indeed contained within message
string, so isInformal
is true
, and thus the respective message is printed.
Changing Case
Sometimes you may need to change the case of a string by converting it to upper case or lower case. Scala provides two string methods for this purpose: toUpperCase
and toLowerCase
, respectively. Both of them do not take any arguments and return a new string with the case conversion applied.
Let's get back to our previous example. Up until now we only checked if "Yo"
is contained within our string, but the string can, for example, contain "yo"
or "yO"
etc. In such case, the program would print that the message is formal, which is incorrect. When the case doesn't matter, it a common technique to convert the string to lower case, and then check for substring.
Let's now apply it to our example:
Main
object Main { def main(args: Array[String]): Unit = { val message = "yO, boss, I have already completed this task." val isInformal = message.toLowerCase().contains("yo") if (isInformal) { println("The message is informal.") } else { println("The message is formal.") } } }
Here, we applied the contains()
method on a newly created string converted to lower case using the toLowerCase()
method and passed "yo"
as the argument in contains()
.
Replacing Substrings
If you want to replace a certain substring in a string, you can use the replace()
method which takes exactly two arguments: which specify a substring in the string (first argument) and a substring which will replace it (second argument). They can either be both strings or chars.
Let's now make a formal message out of our informal message by replacing "Yo"
with "Good afternoon"
:
Main
object Main { def main(args: Array[String]): Unit = { val informalMessage = "Yo, boss, I have already completed this task." val formalMessage = informalMessage.replace("Yo", "Good afternoon") println(formalMessage) } }
Extracting Substring
Now, we'll discuss the substring()
method in Scala which is used to extract a portion of a string (a substring), specified by start (inclusive) and end (exclusive) indices. These two integers are the only two arguments of this method.
The end though is an optional argument, so if not specified, the method will extract a substring from the start index to the end of the string.
Here is an example:
Main
object Main { def main(args: Array[String]): Unit = { val sentence = "Hello, Scala!" val word1 = sentence.substring(7, 12) // without ! println(word1) val word2 = sentence.substring(7) // with ! println(word2) } }
The S
character in the sentence
string is located at index 7
, so that's the first argument of the method. If we want to include the exclamation mark !
(look at word2
), then we don't need to specify the end index. However, if we want to exclude it (look at word1
), then its index should be specified, which is 12
, as the second argument.
Removing Leading and Trailing Whitespace
Sometimes the text data may have various formatting errors, so our goal is to make the strings ready for processing. We can often just use methods similar to replace()
to achieve this goal, however there are cases when it's not an option.
When a string has leading or trailing whitespaces or both, we can use the trim()
method to remove them. This method does not take any parameters and returns a new string. We can simply write string = string.trim()
(provided that string
is a var
), where string
is the name of our original string.
Here is an example:
Main
object Main { def main(args: Array[String]): Unit = { var text = " Just some random text " text = text.trim() println(text) } }
As you can see, everything works as intended.
¡Gracias por tus comentarios!