Enrollments closing soon for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 3 Seats Left
Apply NowLogin using Social Account
     Continue with GoogleLogin using your credentials
There are many methods to work on strings and we will discuss here a few important ones.
int length() - Get string length:
var str1:String = "one"
println("Length is " + str1.length());
String concat(String) - Concat one string to another:
var str1:String = "one"
var str2:String = str1.concat(" two")
println("Combined string is " + str2);
char charAt(int index) - Returns the character at the given index first index being 0:
var str:String = "New York"
println("Char at 5th index is " + str.charAt(4));
String replace(char oldChar, char newChar) - Returns a new string after replacing all occurrences of string oldChar with string newChar:
var str:String = "New York"
println("New string is " + str.replace("York","Shire"));
String replaceAll(char oldChar, char newChar) - Returns a new string after replacing all occurrences of string oldChar with string newChar. It is same as replace
function but additionally, it can also use regular expressions (regex).
var str:String = "New York 1ab2c3"
println("New string is " + str.replaceAll("[0-9]","x"));
To replace multiple chars, use |
separator between patterns.
var str:String = "New York"
// replace all w and k with z
println("New string is " + str.replaceAll("w|k","z"));
String[] split(String regex) - Splits the string around matches of the given regular expression.
var str:String = "New,York,Hello, There"
var strarray = new Array[String](3)
strarray = str.split(",")
println("New string is " + strarray(0));
println(strarray.deep.mkString("\n"))
String substring(int beginIndex, int endIndex) - Returns the substring of a string ending at endIndex-1.
var str:String = "NewxYorkyHello, There"
var str1 = str.substring(4,9)
println("New string is " + str1)
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
No hints are availble for this assesment
Answer is not availble for this assesment
Loading comments...