Scala Basics Tutorial (vi): strings, arrays, collections _scala

Source: Internet
Author: User
Tags locale stringbuffer
To create a string:

The most straightforward way to create a string is to write a method that:

var greeting = "Hello world!";
Or
var greeting:string = "Hello world!";

Whenever you encounter a string in code, the compiler creates a string object and its value in this example using: "Hello world!", but if you like, you can give the string, because here I have alternately shown in the declaration.

Object Test {
Val greeting:string = "Hello, world!"
def main (args:array[string]) {
println (greeting)
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
Hello, world!.
C:/>

As mentioned earlier, the string class is immutable, so once it is created, the string object cannot be changed. If you need to do a lot of character-changing strings, you should use a String builder class (StringBuilder) in Scala. String length:

The method used to obtain information about an object is a known access method. One access method that can be used with a string is the length () method, which returns the number of characters contained in the string object.

Len equals 17 after the following two lines of code are executed:

Object Test {
def main (args:array[string]) {
var palindrome = "Dot saw I was Tod";
var len = Palindrome.length ();
println ("String Length is:" + len);
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
String Length is:17
C:/>
Connection string:

The string class includes methods for connecting two strings:

String1.concat (string2);

This returns a new string that string1 adds string2 to the end of it. You can also use the concat () method with strings, such as:

"My name is". Concat ("Zara");

String comparisons are commonly used in conjunction with the + operator, such as:

"Hello," + "world" + "!"

This will produce:

"Hello, world!."

Let's take a look at the following example:

Object Test {
def main (args:array[string]) {
var str1 = "Dot saw I was";
var str2 = "Tod";
println ("Dot" + str1 + str2);
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
Dot Dot saw I was Tod
C:/>
To create a formatted string:

There are already two methods: the printf () and format () methods use formatted numbers to print output. The string class has a method of an equivalence class, format (), which returns a string object instead of a PrintStream object. Let's take a look at the example below, which uses the printf () method:

Object Test {
def main (args:array[string]) {
var Floatvar = 12.456
var Intvar = 2000
var stringvar = "Hello, scala!"
var fs = printf ("The value of the float variable is" +
"%f, while the value of" +
"Variable is%d, and the string" +
' Is%s ', Floatvar, Intvar, Stringvar
println (FS)
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
String is Hello, scala! ()
C:/>
Method of String:

The following is defined in the Java.lang.String class and you can use the list of methods directly in a Scala program:

SN

Method and Description

1

char charAt (int index)
Returns the character at the specified index

2

int CompareTo (Object o)
This string is compared with another object

3

int CompareTo (String anotherstring)
Compare two strings in dictionary order

4

int comparetoignorecase (String str)
Compares two string dictionary orders, ignoring case differences

5

String concat (String str)
Adds the specified string at the end of this string

6

Boolean contentequals (StringBuffer SB)
Returns true if and only if the character represented by this string has the same sequence as 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)
Tests whether this string ends with the specified suffix.

10

Boolean equals (Object anobject)
Compares the string and the specified object.

11

Boolean equalsignorecase (String anotherstring)
Compares the string to another string, regardless of case.

12

Byte GetBytes ()
Decodes this string to a byte sequence that uses the default character set of the platform and stores the result in a new byte array.

13

Byte[] GetBytes (String charsetname
Decodes this string using the byte sequence of the specified character set and stores 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 destination character array.

15

int Hashcode ()
Returns the hash code for this string.

16

int indexOf (int ch)
Returns the index at which this string specifies the first occurrence of the character.

17

int indexOf (int ch, int fromindex)
Returns the character specified by this string to begin the search for the index at the first occurrence at the specified index.

18

int indexOf (String str)
Returns the index at the first occurrence of the specified child of this string.

19

int indexOf (String str, int fromindex)
Returns the first occurrence of the specified substring in this string, starting at the specified index.

20

String Intern ()
Returns the canonical representation of a string object.

21st

int lastindexof (int ch)
Returns the index at which this string specifies the last occurrence of the character.

22

int lastindexof (int ch, int fromindex)
Returns the index at which the string specifies the last occurrence of the character, and the search begins at the specified index at the back.

23

int LastIndexOf (String str)
Returns the index at the rightmost occurrence of this string's specified child.

24

int LastIndexOf (String str, int fromindex)
Returns the index at the last occurrence of the specified child of this string, and the search begins at the specified index at the back.

25

int Length ()
Returns the length of this string.

26

Boolean matches (String regex)
Determines whether this string matches a regular expression.

27

Boolean Regionmatches (boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests whether two string regions are equal.

28

Boolean regionmatches (int toffset, String other, int ooffset, int len)
Tests whether two string regions are equal.

29

String replace (char Oldchar, char Newchar)
Returns a new string that is generated by replacing all of the strings that appear in the Oldchar with Newchar.

30

String ReplaceAll (string regex, string replacement
Replace this string to match the given regular expression with each substring given the substitution.

31

String Replacefirst (string regex, string replacement)
Replaces this string to match the given regular expression with the given substitution of the first substring.

32

String[] Split (String regex)
This string is to be matched around a given regular expression.

33

String[] Split (String regex, int limit)
This string is the match around which the given regular expression is split.

34

Boolean startswith (String prefix)
Tests whether this string starts with the specified prefix.

35

Boolean startswith (String prefix, int toffset)
Tests whether the beginning of the string begins with the prefix specified by the specified index.

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 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 ()
This string converts to a new character array.

40

String toLowerCase ()
Converts all characters in this string to lowercase by using the default locale's rules.

41

String toLowerCase (Locale Locale)
Converts all characters in this string to lowercase using the rule given by the locale.

42

String toString ()
This object (this is already a string.) ) itself is returned.

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 given locale rule.

45

String Trim ()
Returns a copy of the string, ignored by the beginning and trailing whitespace.

46

Static String valueof (primitive data type X)
Returns a string representation of the passed data type parameter.

Scala provides a data structure-an array that stores contiguous sets of fixed sizes of elements of the same type. Arrays are used to store collections of data, but it is often more useful to think of an array as a collection of variables of the same type.

Takes a declaration of a single variable, such as NUMBER0, Number1, ..., and Number99, declaring an array variable, such as a number, and using numbers[0],numbers[1],...,numbers[99 to represent a single variable. This tutorial describes how to declare an array variable, create an array, and an array of process variables that use an index. The index of the first element of the array is the number 0 and the last element's index is the total of the elements minus 1. Declaring an array variable:

To use an array of programs, you must declare a variable to refer to the array, and you must specify the type that the array variable can reference. The following is a syntax declaration array variable:

var z:array[string] = new Array[string] (3)
Or
var z = new Array[string] (3)

Here, Z is declared as an array of strings, accommodating up to three elements. You can assign a value to a separate element or you can access a single element, which can be done by using a command similar to the following:

Z (0) = "Zara"; Z (1) = "Nuha"; Z (4/2) = "Ayan"

Here, the last example shows that a generic index can be an expression that produces a full number. There is another way to define an array:

var z = Array ("Zara", "Nuha", "Ayan")

The following figure shows the array mylist. Here, the MyList has 10 double values, and the index is from 0 to 9.

Working with arrays:

When dealing with array elements, we often use loops because the elements in all arrays have the same type, and the size of the array is known. Here is a complete example showing how to create, initialize, and process arrays:

Object Test {
def main (args:array[string]) {
var myList = Array (1.9, 2.9, 3.4, 3.5)
Print all the array elements
for (x <-myList) {
println (x)
}
Summing all elements
var total = 0.0;
for (i <-0 to (mylist.length-1)) {
Total + + myList (i);
}
println ("Total are" + total);
Finding the largest element
var max = myList (0);
for (I <-1 to (mylist.length-1)) {
if (myList (i) > max) max = MyList (i);
}
println ("Max is" + max);
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
C:/>
Multidimensional Arrays:

There are many situations where you need to define and use multidimensional arrays (that is, an array of elements). For example, an instance of a matrix and a table structure can be implemented as a two-dimensional array.

Scala does not directly support multidimensional arrays and provides a variety of ways to handle arrays of any size. The following is an instance of the defined two-dimensional array:

var Mymatrix = Ofdim[int] (3,3)

This is an array with an array of 3 elements with each integer that has three elements. The following code shows how to handle multidimensional arrays:

Import Array._
Object Test {
def main (args:array[string]) {
var Mymatrix = Ofdim[int] (3,3)
Build a matrix
for (i <-0 to 2) {
For (J <-0 to 2) {
Mymatrix (i) (j) = J;
}
}
Print two dimensional array
for (i <-0 to 2) {
For (J <-0 to 2) {
Print ("" + Mymatrix (i) (j));
}
println ();
}
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
0 1 2
0 1 2
0 1 2
C:/>
Join Arrays:

The following is an example of using the Concat () method to connect two arrays. You can pass multiple arrays as parameters to the Concat () method.

Import Array._
Object Test {
def main (args:array[string]) {
var myList1 = Array (1.9, 2.9, 3.4, 3.5)
var myList2 = Array (8.9, 7.9, 0.4, 1.5)
var myList3 = concat (MyList1, MyList2)
Print all the array elements
for (x <-myList3) {
println (x)
}
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
1.9
2.9
3.4
3.5
8.9
7.9
0.4
1.5
C:/>
To create a range array:

The following is an example, which allows you to use the range () method to produce an array that contains an integer sequence that is added to a given range. You can use the last parameter to create a sequence; If you do not use the last argument, then one step is assumed to be 1.

Import Array._
Object Test {
def main (args:array[string]) {
var myList1 = range (10, 20, 2)
var myList2 = range (10,20)
Print all the array elements
for (x <-myList1) {
Print ("" + x)
}
println ()
for (x <-myList2) {
Print ("" + x)
}
}
}

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
10 12 14 16 18
10 11 12 13 14 15 16 17 18 19
C:/>
Array methods in Scala:

The following are important ways to use arrays at the same time. As shown above, you must import the Array._ package before using any of the mentioned methods. For a complete list of available methods, use the official files in Scala.

SN

Method and Description

1

def apply (X:t, xs:t*): Array[t]
Creates a T object where t can be unit, Double, Float, Long, Int, Char, Short, Byte, and Boolean arrays.

2

def Concat[t] (xss:array[t]*): Array[t]
Connect all arrays into an array.

3

def copy (Src:anyref, Srcpos:int, Dest:anyref, Destpos:int, length:int): unit
Copy one array to another. Equivalent to Java system.arraycopy (SRC, Srcpos, dest, Destpos, length).

4

def Empty[t]: array[t]
Returns an array of length 0

5

def Iterate[t] (Start:t, Len:int) (f: (t) => T): array[t]
Returns an array that contains a function that is repeated to the initial value.

6

def Fill[t] (n:int) (elem: => T): array[t]
Returns an array of the number of occurrences of the calculated results of some elements.

7

def Fill[t] (N1:int, N2:int) (elem: => T): Array[array[t]]
Returns a two-dimensional array that contains the number of calculated results for some elements.

8

def Iterate[t] (Start:t, Len:int) (f: (t) => T): array[t]
Returns an array that contains a function that is repeated to the initial value.

9

def Ofdim[t] (n1:int): Array[t]
Creates the dimensions given by the array.

10

def Ofdim[t] (N1:int, N2:int): Array[array[t]]
A 2-d array was created

11

def Ofdim[t] (N1:int, N2:int, N3:int): Array[array[array[t]]
Create a 3-D array

12

def range (Start:int, End:int, Step:int): Array[int]
Returns an array that contains interval values such as integer intervals.

13

def range (Start:int, end:int): Array[int]
Returns an array of the included ranges that increase the sequence of integers.

14

def Tabulate[t] (N:int) (f: (Int) => T): array[t]
Returns an array of integer values that contain the value of a given function that is longer than the range starting at 0.

15

def Tabulate[t] (N1:int, N2:int) (f: (int, int) => T): Array[array[t]]
Returns a two-dimensional array containing the value of the given function that exceeds the integer value starting at 0.

Scala has a rich set of collection libraries. A collection is a container for things. These containers can be sequenced, linear sets like List, Tuple, Option, map, and so on set of items can have any number of elements or bounded to 0 or one element (for example, option).

The collection may be strict or lazy. Lazy collections may not consume memory until they are accessed, just like a range element. In addition, the collection can be mutable (the referenced content can be changed) or invariant (a reference to something that never changes). It is important to note that immutable collections may contain mutable items.

For some problems, variable collections work better and work better for immutable collections. If you have questions, it's best to start with an invariant set and change if you need to.

This chapter gives you the most commonly used collection types for information about these collections and the most frequently used operations.

SN

Collection usage Instructions

1

Scala Lists
Scala's list[t] is a list of types T

2

Scala Sets
A set is a collection of different elements of the same type of pairing.

3

Scala Maps
A mapping is a collection of key/value pairs. Any value can be retrieved based on its key.

4

Scala tuples
Unlike arrays or lists, tuples can hold different types of objects.

5

Scala Options
OPTION[T] provides a container for 0 or one element of a given type.

6

Scala iterators
An iteration is not a collection, but an element of one of the accessed collections. Example:

The following code fragment is a simple example to define all of the above collection types:

Define List of integers.
Val x = List (1,2,3,4)
Define a set.
var x = Set (1,3,5,7)
Define a map.
Val x = Map ("One"-> 1, "Two"-> 2, "three"-> 3)
Create a tuple of two elements.
Val x = ("Scala")
Define an option
Val X:option[int] = Some (5)

A class is a blueprint for an object. Once you define a class, you can create an object from the class blueprint using the keyword new. Here's a simple syntax for defining a class in Scala:

Class Yiibai (Xc:int, Yc:int) {
var x:int = XC
var y:int = YC
def move (Dx:int, Dy:int) {
x = x + dx
y = y + dy
println ("Yiibai x Location:" + x);
println ("Yiibai y location:" + y);
}
}

This class defines two variables x and Y and methods: Move, no return value. Class variables are called, and the fields and methods of the class are called class methods.

The class name can be used as a constructor for a class and can take some parameters. The code above defines the parameters of two constructors: XC and YC; they are all visible within the body of the class.

As mentioned earlier, you can use the keyword new to create an object, and then you can access the fields and methods of the class as shown in the following example:

Import Java.io._
Class Yiibai (Val xc:int, Val yc:int) {
var x:int = XC
var y:int = YC
def move (Dx:int, Dy:int) {
x = x + dx
y = y + dy
println ("Yiibai x Location:" + x);
println ("Yiibai y location:" + y);
}
}
Object Test {
def main (args:array[string]) {
Val pt = new Yiibai (10, 20);
Move to a new location
Pt.move (10, 10);
}
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Yiibai x location:20
Yiibai y location:30
 c:/> from:http://www.yiibai.com/scala/scala_basic_syntax.html 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.