Latest web development tutorials

Scala String

The following examples will assign a string constant:

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

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

The above examples defines a variable greeting, a string constant, it is of type String (java.lang.String).

In Scala, type string is actually Java String, it does not have the String class.

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

But other objects, such as an array is a variable object. Next, we will introduce a method common java.lang.String.


Creating strings

Create a string examples are as follows:

var greeting = "Hello World!";

或

var greeting:String = "Hello World!";

You do not specify the String type to a string because Scala compiler will automatically infer the type of the string to String.

Of course, we can also declare a string displayed directly as String type, as examples:

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

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

Implementation of the above code, the output is:

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

As we mentioned earlier String objects are immutable, if you need to create a string can be modified, you can use the String Builder class, the following examples:

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

Running instance »

Implementation of 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 string length:

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

Implementation of the above code, the output is:

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

String concatenation

String class using the concat () method to connect two strings:

string1.concat(string2);

Examples Demo:

scala> "本教程官网: ".concat("www.w3big.com");
res0: String = 本教程官网: www.w3big.com

Similarly, you can also use the plus sign (+) to connect:

scala> "本教程官网: " + " www.w3big.com"
res1: String = 本教程官网:  www.w3big.com

Let's look at a complete example:

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

Implementation of the above code, the output is:

$ scalac Test.scala
$ scala Test
本教程官网:www.w3big.com
本教程的 Slogan 为:学的不仅是技术,更是梦想!

Create a formatted string

String class, you can use the printf () method to format string output, String format () method returns the String object rather than a PrintStream object. The following example demonstrates the printf () method of use:

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

Implementation of the above code, the output is:

$ scalac Test.scala
$ scala Test
浮点型变量为 12.456000, 整型变量为 2000, 字符串为  本教程!()

String Methods

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

No. Method and Description
1

char charAt (int index)

Returns the character at the specified position

2

int compareTo (Object o)

Compare string objects

3

int compareTo (String anotherString)

Compares two strings lexicographically

4

int compareToIgnoreCase (String str)

Compares two strings lexicographically, ignoring case

5

String concat (String str)

The end of the specified string connected to this string

6

boolean contentEquals (StringBuffer sb)

This string to the specified StringBuffer to compare.

7

static String copyValueOf (char [] data )

Returns String array represents the character sequence

8

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

Returns String array represents the character sequence

9

boolean endsWith (String suffix)

Tests if this string ends with the specified suffix

10

boolean equals (Object anObject)

This string to the specified object comparison

11

boolean equalsIgnoreCase (String anotherString)

Compare this String to another String, ignoring case considerations

12

byte getBytes ()

Using the platform's default character set this String encoded byte sequence and stores the result into a new byte array

13

byte [] getBytes (String charsetName

Using the specified character set this String encoded byte sequence and stores the result into a new byte array

14

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

Since then, the character string is copied to the destination character array

15

int hashCode ()

Returns the hash code for this string

16

int indexOf (int ch)

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

17

int indexOf (int ch, int fromIndex )

Shuttle Returns the index within this string of the specified character appears at first, from the specified index to start the search

18

int indexOf (String str)

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

19

int indexOf (String str, int fromIndex )

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

20

String intern ()

Returns a string representation of the object standardization

twenty one

int lastIndexOf (int ch)

Returns the characters in this string of the last index appears

twenty two

int lastIndexOf (int ch, int fromIndex )

Returns the specified character index within this string of the last occurrence of the specified index from the beginning of the reverse search

twenty three

int lastIndexOf (String str)

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

twenty four

int lastIndexOf (String str, int fromIndex )

Returns the specified substring in this string at the last occurrence of the index, starting at the specified index of reverse search

25

int length ()

Returns the length of this string

26

boolean matches (String regex)

Are inform this string matches the given regular expression

27

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

Tests if two string regions are equal

28

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

Tests if two string regions are equal

29

String replace (char oldChar, char newChar )

It returns a new string that is by replacing all oldChar this string with newChar obtained

30

String replaceAll (String regex, String replacement

Substring with the given replacement string replaces all matching the given regular expression

31

String replaceFirst (String regex, String replacement )

First substring with a given replacement Replace this string matches the given regular expression

32

String [] split (String regex)

According to the given regular expression matching split this string

33

String [] split (String regex, int limit)

According to match the given regular expression to split this string

34

boolean startsWith (String prefix)

Tests if this string starts with the specified prefix

35

boolean startsWith (String prefix, int toffset )

Substring test this string beginning at the specified index starts with the specified prefix.

36

CharSequence subSequence (int beginIndex, int endIndex )

It returns a new character sequence that is a subsequence of this sequence

37

String substring (int beginIndex)

It 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 ()

Using the default locale of the rules in this String all the characters are converted to lowercase

41

String toLowerCase (Locale locale)

Given Locale rules in this String all the characters are converted to lowercase

42

String toString ()

Returns this object itself (which is already a string!)

43

String toUpperCase ()

Using the default locale of the rules in this String all the characters are converted to uppercase

44

String toUpperCase (Locale locale)

Given Locale rules in this String all the characters are converted to uppercase

45

String trim ()

Removes the specified string from beginning to end whitespace

46

static String valueOf (primitive data type x )

Returns a string representation of the type of the parameter