![]() |
VOOZH | about |
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created.
There are two ways to create a string in Scala:
var str = "Hello! GFG" or val str = "Hello! GFG"
var str: String = "Hello! GFG" or val str: String = "Hello! GFG"
Note: If you need to append to the original string, then use StringBuilder class.
Example:
Output:
Hello! GFG GeeksforGeeks
An accessor method is those methods which are used to find the information about the object. So, a length() method is the accessor method in Scala, which is used to find the length of the given string. Or in other words, length() method returns the number of characters that are present in the string object.
Syntax:
var len1 = str1.length();
Example:
Output:
String 1:Hello! GFG, Length :10 String 2:GeeksforGeeks, Length :13
when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. You can also use '+' operator to concatenate two strings.
Syntax:
str1.concat(str2);
or
Syntax:
"welcome" + "GFG"
Example:
Output:
String 1:Welcome! GeeksforGeeks String 2: to Portal New String :Welcome! GeeksforGeeks to Portal This is the tutorial of Scala language on GFG portal
When you required format number or values in your string you will use printf() or format() methods. Other than these methods, String class also provides a methods named as format() method, this method return a String object instead of PrintStream object.
Example:
Output:
Ankita , Scala|Strings, 130
| Function | Description |
|---|---|
| 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. |