Easy Tutorial
❮ Scala Loop Types Scala Arrays ❯

Scala Strings

The following example assigns a string to a constant:

Example

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

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

The above example defines the variable greeting, a string constant, with its type as String (java.lang.String).

In Scala, the type of a string is actually Java String, and there is no String class in Scala itself.

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

However, other objects, such as arrays, are mutable objects. We will introduce commonly used java.lang.String methods next.


Creating Strings

Create string instances as follows:

var greeting = "Hello World!";

or

var greeting: String = "Hello World!";

You do not necessarily have to specify the String type for a string, as the Scala compiler will automatically infer the type of the string as String.

Of course, we can also explicitly declare the string as a String type, as in the following example:

Example

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

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

Executing the above code will produce the output:

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

As we mentioned earlier, String objects are immutable. If you need to create a modifiable string, you can use the StringBuilder class, as in the following example:

Example

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

Executing the above code will produce the output:

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

String Length

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

Example

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

Executing the above code will produce the output:

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

String Concatenation

In the String class, the concat() method is used to concatenate two strings:

string1.concat(string2);

Example demonstration:

scala> "tutorialpro.org官网: ".concat("www.tutorialpro.org")
res0: String = tutorialpro.org官网: www.tutorialpro.org

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

scala> "tutorialpro.org官网: " + " www.tutorialpro.org"
res1: String = tutorialpro.org官网:  www.tutorialpro.org

Let's look at a complete example:

Example

object Test {
    def main(args: Array[String]) {
        var str1 = "tutorialpro.org官网:"
        var str2 = "www.tutorialpro.org"
        var str3 = "tutorialpro.org的 Slogan 为:"
        var str4 = "学的不仅是技术,更是梦想!"
        println(str1 + str2)
        println(str3.concat(str4))
    }
}

Executing the above code will produce the output:

$ scalac Test.scala
$ scala Test
tutorialpro.org官网:www.tutorialpro.org
tutorialpro.org的 Slogan 为:学的不仅是技术,更是梦想!

Creating Formatted Strings

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

Example

object Test {
    def main(args: Array[String]) {
        var floatVar = 12.456
        var intVar = 2000
        var stringVar = "tutorialpro.org!"
        var fs = printf("浮点型变量为 " +
                       "%f, 整型变量为 %d, 字符串为 " +
                       " %s", floatVar, intVar, stringVar)
        println(fs)
    }
}

Executing the above code will produce the output:

``` $ scalac Test.scala $ scala Test 浮点型变量为 12.456000, 整型变量为 2000, 字符串为 | 33 | String[] split(String regex, int limit) Splits this string by the matches of the given regular expression | 34 | boolean startsWith(String prefix) Tests if this string starts with the specified prefix | 35 | boolean startsWith(String prefix, int toffset) Tests if the substring of this string beginning at the specified index starts with the specified prefix | 36 | CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence | 37 | String substring(int beginIndex) Returns a new string that is a substring of this string | 38 | String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string | 39 | char[] toCharArray() Converts this string to a new character array | 40 | String toLowerCase() Converts all characters in this String to lowercase using the rules of the default locale | 41 | String toLowerCase(Locale locale) Converts all characters in this String to lowercase using the rules of the given Locale | 42 | String toString() Returns this object itself (it is already a string!) | 43 | String toUpperCase() Converts all characters in this String to uppercase using the rules of the default locale | 44 | String toUpperCase(Locale locale) Converts all characters in this String to uppercase using the rules of the given Locale | 45 | String trim() Removes leading and trailing whitespace from the specified string | 46 | static String valueOf(primitive data type x) Returns the string representation of the specified primitive data type argument

❮ Scala Loop Types Scala Arrays ❯