WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Scala - Strings


Strings are very useful objects, in the rest of this section, we present important methods of java.lang.String class.

The following example assigns a string to a constant:

object Test {
   Val greeting: String = "Hello,World!"

   def main(args: Array[String]) {
      Println( greeting )
   }
}

The above example defines the variable greeting as a string constant whose type is String (java.lang.String).

In Scala, the type of a string is actually a Java String, which itself has no String class.

In Scala, a String is an immutable object, so the object cannot be modified. This means that if you modify the string you will generate a new string object.

But other objects, such as arrays, are mutable objects. Next we will introduce the commonly used java.lang.String method.

Create a string

Create a string instance as follows:

var greeting = "Hello World!";

 or

var greeting:String = "Hello World!";

You don't necessarily specify a String type for a string because the Scala compiler automatically infers that the string is of type String.

Of course, we can also directly display the declaration string as a String type, as in the following example:

object Test {
   val greeting: String = "Hello, World!"

   def main(args: Array[String]) {
      println( greeting )
   }
}

Execute the above code, The output is:

$ scalac Test.scala
$ scala Test
Hello, world!

We mentioned earlier that the String object is immutable. If you need to create a string that can be modified, you can use the String Builder class, as in the following example:

object Test {
   def main(args: Array[String]) {
      val buf = new StringBuilder;
      buf += 'a'
      buf ++= "bcdef"
      println( "buf is : " + buf.toString );
   }
}

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
buf is : abcdef

string length

We can use the length() method to get the length of the string:

object Test {
   def main(args: Array[String]) {
      var palindrome = "www.welookups.com";
      var len = palindrome.length();
      println( "String Length is : " + len );
   }
}

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
String Length is : 14

String connection

The String class uses the concat() method to concatenate two strings:

string1.concat(string2);

Instance demo:

scala> "welookups tutorial official website: ".concat("www.welookups.com");
res0: String = welookups tutorial official website: www.welookups.com

You can also use the plus sign (+) to connect:

scala> "welookups tutorial official website: " + " www.welookups.com"
res1: String = welookups tutorial official website:  www.welookups.com

Let's see a complete example:

object Test {
   def main(args: Array[String]) {
      var str1 = "welookups tutorial official website:";
      var str2 =  "www.welookups.com";
      var str3 =  "welookups tutorial Slogan for:";
      var str4 =  "Learning is not only technology, but also a dream.!";
      println( str1 + str2 );
      println( str3.concat(str4) );
   }
}

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
welookups tutorial official website:www.welookups.com
welookups tutorial Slogan For: learning is not only technology, but also a dream.!

Create a formatted string

In the String class you can use the printf() method to format a string and output it. The String format() method can return a String object instead of a PrintStream object. The following example demonstrates the use of the printf() method:

object Test {
   def main(args: Array[String]) {
      var floatVar = 12.456
      var intVar = 2000
      var stringVar = "welookups Tutorial!"
      var fs = printf("Floating variable is "  +
                   "%f, the integer variable is %d, the string is " +
                   " %s", floatVar, intVar, stringVar)
      Println(fs)
   }
}

Execute the above code, the output is:

$ scalac Test.< /span>scala
$ scala Test
Float variable is 12.456000, The integer variable is  < Span class="lit">2000, string is   Tutorial!()

String method

The following table lists the commonly used methods in java.lang.String , which you can use in Scala:

serial number method and description
1

char charAt(int index)

Return the character at the specified location

2

int compareTo(Object o)

Comparing strings and objects

3

int compareTo(String anotherString)

Compare two strings in lexicographic order

4

int compareToIgnoreCase(String str)

Compare two strings in lexicographic order, regardless of capitalization

5

String concat(String str)

Connect the specified string to the end of this string

6

boolean contentEquals(StringBuffer sb)

Compare this string with the specified StringBuffer.

7

static String copyValueOf(char[] data)

Returns a String representing the sequence of characters in the specified array

8

static String copyValueOf(char[] data, int offset, int count)

Returns a String representing the sequence of characters in the specified array

9

boolean endsWith(String suffix)

Test if this string ends with the specified suffix

10

boolean equals(Object anObject)

Compare this string with the specified object

11

boolean equalsIgnoreCase(String anotherString)

Compare this String with another String, regardless of case

12

byte getBytes()

Encode this String as a byte sequence using the platform's default character set and store the result in a new byte array

13

byte[] getBytes(String charsetName

Encode this String as a byte sequence using the specified character set and store the result in a new byte array

14

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

Copy characters from this string to the target character array

15

int hashCode()

Returns a hash code for this string

16

int indexOf(int ch)

Returns the index of the first occurrence of the specified character in this string

17

int indexOf(int ch, int fromIndex)

Returns the index at the first occurrence of the specified character in this string, starting from the specified index

18

int indexOf(String str)

Returns the index of the first occurrence of the specified substring in this string

19

int indexOf(String str, int fromIndex)

Returns the index of the first occurrence of the specified substring in this string, starting with the specified index

20

String intern()

Returns the canonical representation of a string object

21

int lastIndexOf(int ch)

Returns the index of the last occurrence of the specified character in this string

22

int lastIndexOf(int ch, int fromIndex)

Returns the index of the last occurrence of the specified character in this string, starting a reverse search from the specified index

23

int lastIndexOf(String str)

Returns the index where the specified substring appears at the far right of this string

24

int lastIndexOf(String str, int fromIndex)

Returns the index of the last occurrence of the specified substring in this string, starting from the specified index and searching backwards

25

int length()

Return the length of this string

26

boolean matches(String regex)

Tell if this string matches the given regular expression

27

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

Test whether two string regions are equal

28

boolean regionMatches(int toffset, String other, int ooffset, int len)

Test whether two string regions are equal

29

String replace(char oldChar, char newChar)

returns a new string, which is obtained by replacing all oldChars that appear in this string with newChar

30

String replaceAll(String regex, String replacement

Replace this string with all substrings matching the given regular expression with the given replacement

31

String replaceFirst(String regex, String replacement)

Replace this string with the given replacement to match the first substring of the given regular expression

32

String[] split(String regex)

Split this string based on the match of the given regular expression

33

String[] split(String regex, int limit)

Split this string based on matching given regular expressions

34

boolean startsWith(String prefix)

Test if this string starts with the specified prefix

35

boolean startsWith(String prefix, int toffset)

Test whether the string starting with the specified index starts with the specified prefix.

36

CharSequence subSequence(int beginIndex, int endIndex)

returns a new sequence of characters that is a subsequence of this sequence

37

String substring(int beginIndex)

returns a new string, which is a substring of this string

38

String substring(int beginIndex, int endIndex)

Returns a new string, which is a substring of this string

39

char[] toCharArray()

Convert this string to a new character array

40

String toLowerCase()

Convert all characters in this String to lowercase using the rules of the default locale

41

String toLowerCase(Locale locale)

Convert all characters in this String to lowercase using the rules of the given Locale

42

String toString()

Return this object itself (it is already a string!)

43

String toUpperCase()

Convert all characters in this String to uppercase using the rules of the default locale

44

String toUpperCase(Locale locale)

Convert all characters in this String to uppercase using the rules of the given Locale

45

String trim()

Delete the leading and trailing whitespace of the specified string

46

static String valueOf(primitive data type x)

Returns a string representation of the specified type parameter