Scala: Strings Cheat Sheet

Creating a String

var str = "Hello world!";

or

var str:String = "Hello world!";

Note: If you need to append to the original string, then use StringBuilder class.

Get length of the string

var len = str.length();

Concatenating strings in Scala

The String class includes a method for concatenating two strings −

str1.concat(string2);

Or

Strings are more commonly concatenated with the + operator:

"My name is:" + " John" + "!"

Creating format string

Example:

// Scala program to illustrate how to
// Creating format string
object Main
{

   // two strings 
   var stringVar = "Hello world!"
   var intVar = 14
   var floatVar = 14.07

   // Main function 
   def main(args: Array[String]) 
   { 

       // using format() function 
       println("%s, %d, %f".format(stringVar, intVar, floatVar)); 
   } 
}

=> Output

Hello world!, 14, 14.07

Important string functions

FunctionDescription
char charAt(int index)This function returns the character at the given index.
String replace(char ch1, char ch2)This function returns a new string in which the element of ch1 is replaced by the ch2.
String[] split(String reg)This function splits the string around matches of the given regular expression.
String substring(int i)This function returns a new string that is a substring of the given string.
String trim()This function returns a copy of the string, with starting and ending whitespace removed.
boolean startsWith(String prefix)This function is used to check if the given string starts with the specified prefix or not.

Leave a Reply

Your email address will not be published. Required fields are marked *