English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Chaînes Scala

L'exemple suivant affecte une chaîne de caractères à une constante :

object Test {
   val greeting: String = "Hello,World!"
   def main(args: Array[String]) {
      println( greeting )
   }
}

L'exemple suivant définit la variable greeting, une constante de chaîne, de type String (java.lang.String).

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

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 the commonly used java.lang.String methods.

String creation

String creation examples are as follows:

var greeting = "Hello World!";
or
var greeting:String = "Hello World!";

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

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

object Test {
   val greeting: String = "Hello, World!"
   def main(args: Array[String]) {
      println( greeting )
   }
}

After executing the above code, the output result is:

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

As mentioned earlier, String objects are immutable. If you need to create a modifiable string, you can use the StringBuilder 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 );
   }
}

After executing the above code, the output result is:

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

String length

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

Online example

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

After executing the above code, the output result is:

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

String concatenation

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

string1.concat(string2);

Example demonstration:

scala> "Base tutorial website official website: ".concat("fr.oldtoolbag.com");
res0: String = Base tutorial website official website: fr.oldtoolbag.com

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

scala> "Base tutorial website official website: " + " fr.oldtoolbag.com"
res1: String = Basic Tutorial Website official website:   fr.oldtoolbag.com

Let's look at a complete example:

object Test {
   def main(args: Array[String]) {
      var str1 = "Basic Tutorial Website official website: ";
      var str2 =   "fr.oldtoolbag.com";
      var str3 =   "The slogan of Basic Tutorial Website is: ";
      var str4 =   "Learn the basics, and you can go further!";
      println(   str1 + str2 );
      println(   str3.concat(str4);
   }
}

After executing the above code, the output result is:

$ scalac Test.scala
$ scala Test
Basic Tutorial Website official website: fr.oldtoolbag.com
The slogan of Basic Tutorial Website is: Learn the basics, and you can go further!

Create a formatted string

In the String class, you can use the printf() method to format strings and output them. The String format() method returns 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 = "Basic Tutorial Website!"
      var fs = printf("The floating-point variable is " +
                   "%f, the integer variable is  %d, the string is " +
                   "   %s", floatVar, intVar, stringVar)
      println(fs)
   }
}

After executing the above code, the output result is:

$ scalac Test.scala
$ scala Test
The floating-point variable is 12.456000, the integer variable is 2000, the string is   Basic Tutorial Website!()

String methods

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

Serial numberMethod and description
1

char charAt(int index)

Return the character at the specified position

2

int compareTo(Object o)

Compare a string with an object

3

int compareTo(String anotherString)

Compare two strings in dictionary order

4

int compareToIgnoreCase(String str)

Compare two strings in dictionary order without considering case

5

String concat(String str)

Connect the specified string to the end of this string

6

boolean contentEquals(StringBuffer sb)

compare cette chaîne avec un StringBuffer spécifié.

7

static String copyValueOf(char[] data)

retourne la chaîne qui représente la séquence de caractères spécifiée dans l'array spécifié

8

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

retourne la chaîne qui représente la séquence de caractères spécifiée dans l'array spécifié

9

boolean endsWith(String suffix)

test si cette chaîne se termine par le suffixe spécifié

10

boolean equals(Object anObject)

compare cette chaîne avec un objet spécifié

11

boolean equalsIgnoreCase(String anotherString)

compare cette chaîne avec une autre chaîne sans considérer la casse

12

byte getBytes()

encode cette chaîne en séquence de bytes avec le jeu de caractères par défaut du système, et stocke le résultat dans un nouveau tableau de bytes

13

byte[] getBytes(String charsetName

encode cette chaîne en séquence de bytes avec le jeu de caractères spécifié, et stocke le résultat dans un nouveau tableau de bytes

14

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

copie les caractères à partir de cette chaîne dans un tableau de caractères cible

15

int hashCode()

retourne le code hash de cette chaîne

16

int indexOf(int ch)

retourne l'indice de la première apparition du caractère spécifié dans cette chaîne

17

int indexOf(int ch, int fromIndex)

retourne l'indice de la première apparition du caractère spécifié dans cette chaîne, en commençant par l'indice spécifié

18

int indexOf(String str)

retourne l'indice de la première apparition de la sous-chaîne spécifiée dans cette chaîne

19

int indexOf(String str, int fromIndex)

retourne l'indice de la première apparition de la sous-chaîne spécifiée dans cette chaîne, à partir de l'indice spécifié

20

String intern()

retourne la représentation normalisée de l'objet chaîne

21

int lastIndexOf(int ch)

retourne l'indice de la dernière apparition du caractère spécifié dans cette chaîne

22

int lastIndexOf(int ch, int fromIndex)

Return the index of the last occurrence of the specified character in this string, starting the search from the specified index backwards

23

int lastIndexOf(String str)

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

24

int lastIndexOf(String str, int fromIndex)

Return the index of the last occurrence of the specified substring in this string, starting the search from the specified index backwards

25

int length()

Return the length of this string

26

boolean matches(String regex)

Inform whether this string matches the given regular expression

27

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

Test if two string regions are equal

28

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

Test if two string regions are equal

29

String replace(char oldChar, char newChar)

Return a new string that is obtained by replacing all occurrences of oldChar in this string with newChar

30

String replaceAll(String regex, String replacement

Replace all occurrences of substrings of this string that match the given regular expression with the given replacement

31

String replaceFirst(String regex, String replacement)

Replace the first substring of this string that matches the given regular expression with the given replacement

32

String[] split(String regex)

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

33

String[] split(String regex, int limit)

Split this string based on the given regular expression

34

boolean startsWith(String prefix)

Test if this string starts with the specified prefix

35

boolean startsWith(String prefix, int toffset)

Test if the substring of this string starting from the specified index starts with the specified prefix.

36

CharSequence subSequence(int beginIndex, int endIndex)

Retourne un nouveau sous-ensemble de caractères, qui est un sous-ensemble de ce sous-ensemble

37

String substring(int beginIndex)

Retourne une nouvelle chaîne, qui est un sous-chaîne de cette chaîne

38

String substring(int beginIndex, int endIndex)

Retourne une nouvelle chaîne, qui est un sous-chaîne de cette chaîne

39

char[] toCharArray()

Convertit cette chaîne en un nouveau tableau de caractères

40

String toLowerCase()

Convertit tous les caractères de cette chaîne en minuscules en utilisant les règles du langage par défaut

41

String toLowerCase(Locale locale)

Convertit tous les caractères de cette chaîne en minuscules en utilisant les règles de ce Locale donné

42

String toString()

Retourne cet objet lui-même (il est déjà une chaîne !)

43

String toUpperCase()

Convertit tous les caractères de cette chaîne en majuscules en utilisant les règles du langage par défaut

44

String toUpperCase(Locale locale)

Convertit tous les caractères de cette chaîne en majuscules en utilisant les règles de ce Locale donné

45

String trim()

Supprime les espaces blancs à la tête et à la queue de la chaîne spécifiée

46

static String valueOf(type de données primitif x)

Retourne la représentation en chaîne de caractères de la valeur du type spécifié