Scala String Method with Syntax and Method

Free Scala course with real-time projects Start Now!!

Scala String Method – Object

In this tutorial on Scala String Method, we will discuss the methods defined by the class java.lang.String. Before you proceed with this, you should check out a brief introduction to Strings in Scala.

So, let’s start Scala String Method Tutorial.

List of String Method in Scala with Example

1. char charAt(int index)

This method returns the character at the index we pass to it. Isn’t it so much like Java?

scala> "Ayushi".charAt(1)
res2: Char = y

2. int compareTo(Object o)

This Scala String Method compares a string to another object.

scala> "Ayushi".compareTo("Ayush")
res10: Int = 1

3. int compareTo(String anotherString)

This is like the previous one, except that it compares two strings lexicographically. If they match, it returns 0. Otherwise, it returns the difference between the two(the number of characters less in the shorter string, or the maximum ASCII difference between the two).

scala> "Ayushi".compareTo("Ayushi ")
res3: Int = -1
scala> "Ayushi".compareTo("Ayushi")
res4: Int = 0
scala> "Ayushi".compareTo("ayushi")
res5: Int = -32

Comparing to a different type raises a type-mismatch error.

scala> "Ayushi".compareTo(7)
<console>:12: error: type mismatch;
found   : Int(7)
required: String
      "Ayushi".compareTo(7)
                         ^

4. int compareToIgnoreCase(String str)

int compareToIgnoreCase Scala String Method compares two strings lexicographically, while ignoring the case differences.

scala> "Ayushi".compareToIgnoreCase("ayushi")
res21: Int = 0
scala> "Ayushi".compareToIgnoreCase("ayushi ")
res22: Int = -1
scala> "Ayushi".compareToIgnoreCase("aYushi")
res41: Int = 0

5. String concat(String str)

This will concatenate the string in the parameter to the end of the string on which we call it. We saw this when we talked about strings briefly.

scala> "Ayushi".concat("Sharma")
res23: String = AyushiSharma

6. Boolean contentEquals(StringBuffer sb)

contentEquals compares a string to a StringBuffer’s contents. If equal, it returns true; otherwise, false.

scala> val a=new StringBuffer("Ayushi")
a: StringBuffer = Ayushi
scala> "Ayushi".contentEquals(a)
res24: Boolean = true
scala> "ayushi".contentEquals(a)
res25: Boolean = false

7. Boolean endsWith(String suffix)

This Scala String Method returns true if the string ends with the suffix specified; otherwise, false.

scala> "Ayushi".endsWith("i")
res32: Boolean = true
scala> "Ayushi".endsWith("sha")
res33: Boolean = false

8. Boolean equals(Object anObject)

This Scala String Method returns true if the string and the object are equal; otherwise, false.

scala> val b=Array('A','y','u','s','h','i')
b: Array[Char] = Array(A, y, u, s, h, i)
scala> "Ayushi".equals(b)
res34: Boolean = false
scala> "Ayushi".equals("ayushi")
res35: Boolean = false
scala> "Ayushi".equals("Ayushi")
res36: Boolean = true
scala> val b=Array("Ayushi")
b: Array[String] = Array(Ayushi)
scala> "Ayushi".equals(b)
res37: Boolean = false
scala> "Ayushi".equals(7)
res39: Boolean = false
scala> "7".equals(7)
res40: Boolean = false
scala> "Ayushi".equals("aYushi")
res43: Boolean = false

9. Boolean equalsIgnoreCase(String anotherString)

This is like equals(), except that it ignores case differences.

scala> "Ayushi".equalsIgnoreCase("aYushi")
res42: Boolean = true

10. byte getBytes()

getBytes Scala String Method encodes a string into a sequence of bytes and stores it into a new byte array. It uses the platform’s default charset for this.

scala> "Ayushi".getBytes()
res44: Array[Byte] = Array(65, 121, 117, 115, 104, 105)
scala> "ABCcba".getBytes()
res45: Array[Byte] = Array(65, 66, 67, 99, 98, 97)
scala> " ".getBytes()
res46: Array[Byte] = Array(32)

11. byte[] getBytes(String charsetName)

With a named charset as a parameter, getBytes will use that charset to encode the string.

scala> "Ayushi".getBytes("Unicode")
res47: Array[Byte] = Array(-2, -1, 0, 65, 0, 121, 0, 117, 0, 115, 0, 104, 0, 105)
scala> "Ayushi".getBytes("UTF-8")
res48: Array[Byte] = Array(65, 121, 117, 115, 104, 105)

However, providing an invalid charset name will result in an error:

scala> "Ayushi".getBytes("Union")
java.io.UnsupportedEncodingException: Union
 at java.lang.StringCoding.encode(Unknown Source)
 at java.lang.String.getBytes(Unknown Source)
 ... 28 elided

12. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

This Scala String Method copies characters from the string into the destination character array. scrBegin denotes the index to begin at in the source string, and srcEnd denotes the index to end at in the source string. dstBegin denotes the index to begin at in the destination character array. dst is the destination character array.

scala> var c:Array[Char]=Array('A','y','u','s','h','i')
c: Array[Char] = Array(A, y, u, s, h, i)
scala> var d="01234"
d: String = 01234
scala> d.getChars(2,4,c,2)
scala> c
res57: Array[Char] = Array(A, y, 2, 3, h, i)

13. int hashCode()

This int hashCode method returns a hash code for the string.

scala> "Ayushi".hashCode()
res58: Int = 1976240247
scala> val name="Ayushi"
name: String = Ayushi
scala> name.hashCode()
res60: Int = 1976240247

14. int indexOf(int ch)

This Scala Sring returns the index of the first occurrence of the character ch in the string.

scala> "Banana".indexOf('a')
res61: Int = 1
scala> "Banana".indexOf('n')
res62: Int = 2

15. int indexOf(int ch, int fromIndex)

This is like indexOf, except that it begins searching at the index we specify.

scala> "Banana".indexOf('a',2)
res63: Int = 3

16. int indexOf(String str)

This Scala String Method returns the index of the first occurrence of the substring we specify, in the string.

scala> "Banana".indexOf("na")
res64: Int = 2

17. int indexOf(String str, int fromIndex)

Like the other version of indexOf for a single character, this begins searching at the index we specify.

scala> "Banana".indexOf("na",3)
res66: Int = 4

18. String intern()

intern returns the canonical representation for the string object.

scala> "Hello,\n\tWorld".intern()
res69: String =
Hello,
       World

19. int lastIndexOf(int ch)

Unlike indexOf, this Scala String Method returns the index of the last occurrence of the character we specify.

scala> "Banana".lastIndexOf('n')
res70: Int = 4

20. int lastIndexOf(int ch, int fromIndex)

This is like lastIndexOf, except that it begins searching backwards(right to left), starting at the index we specify.

scala> "Banana".lastIndexOf('n',1)
res71: Int = -1
Here, it returns -1 because it couldn’t find ‘n’.
scala> "Banana".lastIndexOf('n',3)
res72: Int = 2

21. int lastIndexOf(String str)

This Scala String Method returns the index of the last occurrence of the substring we specify, in the string.

scala> "Banana".lastIndexOf("na")
res73: Int = 4

22. int lastIndexOf(String str, int fromIndex)

This Scala String Method is like the previous method, except that it begins searches at the index we specify, and searches right to left.

scala> "Banana".lastIndexOf("na",3)
res74: Int = 2
scala> "Banana".lastIndexOf("na",2)
res75: Int = 2
scala> "Banana".lastIndexOf("na",1)
res76: Int = -1

23. int length()

This Scala String Method method simply returns the length of a string.

scala> "Ayushi!".length()
res77: Int = 7
scala> "".length()
res78: Int = 0

24. Boolean matches(String regex)

If the string matches the regular expression we specify, this returns true; otherwise, false.

scala> "Ayushi".matches(".i.*")
res80: Boolean = false
scala> "Ayushi".matches(".*i")
res79: Boolean = true

25. Boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len)

If two string regions are equal, this returns true; otherwise, false. ignoreCase, when set to true, will ignore the case differences.

scala> "Ayushi".regionMatches(true,0,"Ayushi",0,4)
res81: Boolean = true
scala> "Ayushi".regionMatches(true,0,"Ayush",0,4)
res82: Boolean = true
scala> "Ayushi".regionMatches(true,0,"Ayush",0,3)
res83: Boolean = true
scala> "Ayushi".regionMatches(true,0,"Ay",0,3)
res84: Boolean = false

26. Boolean regionMatches(int toffset, String other, int offset, int len)

This is like the previous method, except that it doesn’t have ignoreCase.

scala> "Ayushi".regionMatches(0,"Ayu",0,2)
res85: Boolean = true
scala> "Ayushi".regionMatches(0,"Ayu",0,4)
res86: Boolean = false

27. String replace(char oldChar, char newChar)

Replace will replace all occurrences of oldChar in the string with newChar, and return the resultant string.

scala> "Ayushi sharma".replace('s','$')
res87: String = Ayu$hi $harma
scala> "Ayushi Sharma".replace('s','$')
res88: String = Ayu$hi Sharma

28. String replaceAll(String regex, String replacement)

This will replace each substring matching the regular expression. It will replace it with the replacement string we provide.

scala> "potdotnothotokayslot".replaceAll(".ot","**")
res89: String = ********okays**

29. String replaceFirst(String regex, String replacement)

If in the above example, we want to replace only the first such occurrence:

scala> "potdotnothotokayslot".replaceFirst(".ot","**")
res90: String = **dotnothotokayslot

30. String[] split(String regex)

This Scala String Method splits the string around matches of the regular expression we specify. It returns a String array.

scala> "xpotxdotynotzhotokayslot".split(".ot")
res93: Array[String] = Array(x, x, y, z, okays)

31. String[] split(String regex, int limit)

This Scala String Method is like split, except that we can limit the number of members for the array. The last member, then, is whatever part of the string that’s left.

scala> "xpotxdotynotzhotokayslot".split(".ot",2)
res94: Array[String] = Array(x, xdotynotzhotokayslot)
scala> "xpotxdotynotzhotokayslot".split(".ot",5)
res95: Array[String] = Array(x, x, y, z, okayslot)

32. Boolean startsWith(String prefix)

If the string starts with the prefix we specify, this returns true; otherwise, false. This is like endsWith.

scala> "Ayushi".startsWith("Ay")
res97: Boolean = true
scala> "Ayushi".startsWith(" A")
res99: Boolean = false
scala> "Ayushi".startsWith("ayu")
res100: Boolean = false

33. Boolean startsWith(String prefix, int toffset)

If the string starts with the specified prefix at the index we specify, This Scala string method returns true; otherwise, false.

scala> "Ayushi".startsWith("yu",1)
res101: Boolean = true

34. CharSequence subSequence(int beginIndex, int endIndex)

This returns a subsequence from the string, beginning at beginIndex and ending at endIndex.

scala> "Ayushi".subSequence(1,4)
res102: CharSequence = yus

35. String substring(int beginIndex)

This Scala String Method returns the contents of the string beginning at beginIndex.

scala> "Ayushi".substring(3)
res103: String = shi

36. String substring(int beginIndex, int endIndex)

This returns the part of the string beginning at beginIndex and ending at endIndex. Wait, isn’t that the same as subsequence? Check the types of the results:

scala> var a="Ayushi".subSequence(1,4)
a: CharSequence = yus
scala> var b="Ayushi".substring(1,4)
b: String = yus

While one returns a CharSequence, the other returns a String.

37. char[] toCharArray()

This converts the string into a CharArray, and then returns it.

scala> "Ayushi".toCharArray()
res104: Array[Char] = Array(A, y, u, s, h, i)

38. String toLowerCase()

This String Method in Scala converts all characters in the string to lower case, and then returns the resultant string.

scala> "AyU$#I!".toLowerCase()
res105: String = ayu$#i!

39. String toLowerCase(Locale locale)

This is like toLowerCase, except that we can specify the locale to follow the rules of.

40. String toString()

This returns a String object itself.

scala> "7".toString()
res108: String = 7

41. String toUpperCase()

This Scala String Method is like toLowerCase, and converts all characters in the string to upper case.

scala> "Ayushi".toUpperCase()
res109: String = AYUSHI

42. String toUpperCase(Locale locale)

This is like the previous method, except that it will follow the rules of the given locale.

43. String trim()

Trim will elide the leading and trailing whitespaces from the string, and then return it.

scala> "         Ayushi ".trim()
res110: String = Ayushi

So, this was all about Scala String Methods. Hope you like our explanation.

3.Conclusion

These are the 43 methods we can directly call on a String in Scala. Hope we’ve done our job in explaining them efficiently and clearly. Still, had a confusion, feel free to share with us!

Reference

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

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