Scala string


The following example assigns a string value to a constant:

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

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

The above example defines the variable greeting, which is a string constant and its type is String (java.lang.String).

In Scala, the type of string is actually Java String, which does not have a String class itself.

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

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



Create a string

Create a string instance as follows:

var greeting = "Hello World!";

或

var greeting:String = "Hello World!";

You do not have to specify the String type for the string. Because the Scala compiler will automatically infer that the string type is String.

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

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

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

Execute the above code, the output result is:

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

We mentioned before String objects are immutable. If you need to create a string that can be modified, you can use the String Builder class, as shown in the following example:

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

Run instance»

Execute The output result of the above code 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.php.cn";
      var len = palindrome.length();
      println( "String Length is : " + len );
   }
}

Execute the above code, The output result is:

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

String connection

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

string1.concat(string2);

Example demonstration:

scala> "php中文网官网: ".concat("www.php.cn");
res0: String = php中文网官网: www.php.cn

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

scala> "php中文网官网: " + " www.php.cn"
res1: String = php中文网官网:  www.php.cn

Let us see a complete example:

object Test {
   def main(args: Array[String]) {
      var str1 = "php中文网官网:";
      var str2 =  "www.php.cn";
      var str3 =  "php中文网的 Slogan 为:";
      var str4 =  " php中文网";
      println( str1 + str2 );
      println( str3.concat(str4) );
   }
}

Execute the above code, the output result is:

$ scalac Test.scala
$ scala Test
php中文网官网:www.php.cn
php中文网的 Slogan 为: php中文网

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 = "php中文网!"
      var fs = printf("浮点型变量为 " +
                   "%f, 整型变量为 %d, 字符串为 " +
                   " %s", floatVar, intVar, stringVar)
      println(fs)
   }
}

Execute the above code, the output result is:

$ scalac Test.scala
$ scala Test
浮点型变量为 12.456000, 整型变量为 2000, 字符串为  php中文网!()

String method

The following table lists the java Commonly used methods in .lang.String can be used in Scala:

##19202122##23##394041444546
Serial numberMethod and description
1

char charAt(int index)

Returns the character at the specified position

2

int compareTo(Object o)

Compare string and object

3

int compareTo(String anotherString)

Compare two strings in lexicographic order

4

int compareToIgnoreCase(String str)

Compares two strings in lexicographic order, regardless of case

5

String concat(String str)

Concatenate 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)

Return to the specified array String representing the character sequence

8

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

Returns the String representing the character sequence in the specified array

9

boolean endsWith(String suffix)

Test whether this string ends with the specified suffix

10

boolean equals(Object anObject)

Compare this string with the specified object

11

boolean equalsIgnoreCase(String anotherString)

Compares this String with another String, regardless of case

12

byte getBytes()

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

13

byte[] getBytes(String charsetName

Use the specified character set to encode this String into byte sequence 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 the hash code of 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 where the specified character appears for the first time in this string, from the specified Index starts searching

18

int indexOf(String str)

returns the specified subcharacter The index of the first occurrence of string in this string

##int indexOf(String str, int fromIndex)

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

String intern()

Returns the normalized representation of the string object

int lastIndexOf(int ch)

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

int lastIndexOf(int ch, int fromIndex)

Returns the index of the last occurrence of the specified character in this string, from Start reverse search at the specified index

##int lastIndexOf(String str)

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

24
int lastIndexOf(String str, int fromIndex)

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

25

int length()

Returns the length of this string

26

boolean matches(String regex)

Tells whether 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 two strings Are the areas equal?

29

String replace(char oldChar, char newChar)

Return A new string obtained by replacing all occurrences of oldChar in this string with newChar

30

String replaceAll(String regex, String replacement

Use the given replacement to replace all substrings of this string that match the given regular expression

31

String replaceFirst(String regex, String replacement)

Replace this string with the given replacement matching the given regular expression The first substring of

32

String[] split(String regex)

Split this string based on matches of the given regular expression

33

String[] split(String regex , int limit)

Split this string based on matching the given regular expression

34

boolean startsWith(String prefix)

Test whether this string starts with the specified prefix

35

boolean startsWith(String prefix, int toffset)

Tests whether the substring of this string starting at the specified index starts with the specified prefix.

36

CharSequence subSequence(int beginIndex, int endIndex)

Return a new Character sequence, which 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, which is a substring of this string

char[] toCharArray()

Convert this string to a new character array

String toLowerCase()

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

String toLowerCase(Locale locale)

Use the rules of the given Locale to all the values ​​in this String Characters are converted to lowercase

42

String toString()

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

43

##String toUpperCase()

Use the rules of the default locale to this All characters in String are converted to uppercase

##String toUpperCase(Locale locale)

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

String trim( )

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

static String valueOf(primitive data type x)

Returns the string representation of the specified type parameter