Introduction to Scala String

Scala string is an immutable object that means object cannot be modified. Each element of a string is associated with an index number. The first character is associated with the number 0, the second with the number 1, etc. Class java.lang.String contains different predefined functions which are very useful to perform various operations on strings.

var I = “intellipaat”

Some methods are –

  • length – Returns the number of Unicode code units in a string

e.g.

println(I.length)

Output
11

  • charAt – It has an index number as an argument and returns the Char at the specified index.

 e.g.

println(I.charAt(2))

Output
t
 

  • startsWith – Tests whether this string starts with the argument of this method.

e.g.

println(A.startsWith("I"))

Output
True
 

  • endsWith – Tests whether this string ends with the argument of this method.

e.g.

println(I.endsWith("i"))

Output
False
 

  • indexOf – Returns the index within this string object of the first occurrence of the string argument.

e.g.

println(I.indexOf("n"))

Output
1
 

  • substring – Returns a new string that is a substring of this string. It may take one or two arguments. If it takes one argument then substring begins with the specified index to the end of string and if it takes two argument then first specify the starting of string and second string specify the ending of string

e.g.

println(I.substring(1,4))

Output
nte
 

  • concat – This method appends its argument to this string

e.g.

I = I.concat("Hello");
println(A)

Output
intellipaathello
 

  • contains – Examine whether a string contains a particular substring or not.

e.g.

if(I.contains("inte"))
println("contains specified string")

Output
contains specified string

  • replace – It takes two arguments from which first argument is replaced by second argument form the specified string.

e.g.

println(I.replace('a','t'))
println(I)

Output
intellipttt
 

  • toLowerCase – converts all of the characters in this string to lower case.

e.g.

println(I.toLowerCase())

Output
intellipaat
 

  • toUpperCase – converts all of the characters in this string to upper case.

e.g.

println(I.toUpperCase())

Output
INTELLIPAAT
 

  • trim – Returns a copy of the string with leading and trailing whitespace omitted.
  • isEmpty – Returns true if method length returns 0.
  • codePointAt – Returns the Unicode code point at the specified index.
  • toCharArray – Transforms a string into an array
Previous Next

Recommended Videos