"Scala" Scala's string

Source: Internet
Author: User

First, preface

The big data world of Spark, Kafka, Summingbird, etc. are written in the Scala language, and Scala is more refined than Java. Because I am engaged in big data related work, so it is necessary to learn the Scala language, before also learned, but no record, so will forget, feel Scala is indeed more convenient than Java refining a lot, the following with Scala cookbook English version as reference material, From beginning to end combing Scala's relevant knowledge points, also deepen the impression. PS: This is in the study of zookeeper source gap in the cross-learning, not always look at the source too boring.

Second, String

Testing the type of string in Scala's REPL environment can be found to be a string in Java.

So you can use all the methods of string in Java, such as getting the length of a string, connecting multiple strings. In Scala, because string can be implicitly converted to the Stringops type, the string is treated as a sequence of characters, and each character of the string can be traversed using the Foreach method.

You can also use a for loop to iterate through each character by using a string as a sequence of characters

Similarly, you can also use the For loop to iterate through the current byte sequence of a string

Because a string can be used as a character order collection (a sequence of characters), multiple operations can be performed on the collection, such as the filter

  

You can see that the string is filtered and the L character is removed. The filter method is a Stringops method, and this method can be called because the string is implicitly converted to Stringops.

For this implicit conversion, it is defined in the Perdef object.

  New Stringops (x)

  To add a method to a enclosing class

In Java, string is defined as final, that is, you cannot inherit the string class or add any methods, but in Scala we can add methods through implicit conversions, and the following example shows that Scala's string has the properties of string and the attributes of the collection.

The drop method and the Take method are all Scala's sequence (collection) methods, and the Capitalize method is the Stringops method, which is done by implicit conversion.

  2.1 Testing the equality of a string

  1. Description of the problem

You need to compare two strings to determine if they are equal, or they contain the same sequence of characters.

  2. Solution

Defines the following string s1, S2, S3

  

using "= =" for Equality judgment

  

You can see that S1, S2, and S3 are equal, and for a good "= =" method, even if there are parameters empty, no exception is thrown.

If the case is not case-sensitive during the comparison, the string can be converted to uppercase or lowercase for comparison.

  

However, calling the toUpperCase method on an empty string throws an exception.

  

In Java, if you want to compare case-insensitive comparisons of two strings for equality, use the Equalsignorecase method

  

  3. Discussion

In Scala, we use the = = method to determine the equality of objects, which differs from Java in that Java uses the Equals method to determine the equality of two objects, = = To compare two objects with the same object (the memory address is the same). In Scala, the = = method is defined in Anyref (the parent class of all reference types), which first checks for null values and then calls the Equals method of the first object for comparison, so we do not need to check for null values when comparing two strings for equality.

  2.2 Creating multi-line strings

  1. Description of the problem

You want to create multi-line strings in the Scala source code.

  2. Solution

In Scala, you can use three double quotation marks to create a multiline string.

    val S1 = "" "This is        a multiline        String      " ""    println (S1)

  3. Discussion

Use the above method to create a multiline string, but when printing, the result is as follows

This is        a multiline        String

The second and third lines start with a space, and if you need to make the second and third lines of string not start with a space, you can do the following.

    val S1 =      "" "        |  This        | Is a multiline        | String      "". Stripmargin        println (S1)

The results are as follows

Thisis a multilinestring

This is done through |, or using other symbols, such as #, using the Stripmargin method.

    val S1 = "" "This is        #a multiline        #String      " ". Stripmargin (' # ')    println (S1)

The results are as follows

This ISA multilinestring

In the above example, the \ n characters are hidden after the first and second rows of multiline, and when you need to merge a multiline string into a single line, you can use the ReplaceAll method after you use the Stripmargin method to replace all \ n with "".

  

In addition, you can include special characters in a three-quote string without escaping the escape character.

 2.3 Split String

  1. Description of the problem

You need to use split characters to split a string, such as a comma-delimited (CSV) or pipe-delimited file.

  2. Solution

You can use the split method of string to split

  

The Split method returns a string array.

  3. Discussion

The arguments to the split function can be regular expressions, so for CSV files, you can use commas to split strings.

  

As you can see, by "," when you split, the result also contains some spaces, such as "milk", "butter", "Coco puffs", at this point, you need to use the TRIM function to remove the space.

  

We can also use regular expressions to split the string

  

The split method is overloaded, partly from Java's string, and partly from Scala's stringlike, for example, you can call split using a character instead of a string as a parameter, and you're using the Stringlike method

  

At this point, the result of using both a character and a string as a parameter is the same.

  2.4 Replacing a variable with a string

 1. Description of the problem

Like Perl, PHP, and Ruby, you need to replace the variable with a string.

  2. Solution

To use string interpolation in Scala, the letter S is used in front of the string, and variables need to be included in the string, and each variable name is preceded by a $ character.

  

When the letter S is used in front of a string, it means that a processed string literal is being created, that is, you can use the variable directly in the string.

  Use an expression in string literals

In addition to using variables in a string, you can also use an expression in a string, where the expression needs to be enclosed within brackets.

  

  

You can also print the properties of an object using brackets.

  

  S is a method

The s in front of the string literal is actually a method, and using the S method allows you to enjoy the following convenience

· Scala offers other ready-made interpolation functions

· You can customize the string interpolation function

  F string interpolation (printf format)

As mentioned in the discussion, weight is printed as 65, but if you need to add multiple decimal points after weight, you can use the F string interpolation method, which can format the specifier in the string.

  

To use F-string interpolation, you first need to add F before the string and then use the printf format specifier after the variable.

  Coarse interpolation

In addition to using the S and f interpolation methods, Scala includes a coarse interpolation method that preserves special characters in the string.

  

You can see that when you use raw decorated strings, they retain special characters in the string.

The following table lists the most common specifiers

  

  2.5 One character for processing a string at a time

  1. Description of the problem

You need to iterate through each character of the string and do a corresponding operation on each character.

  2. Solution

You can use the map method, the Foreach method, the For loop, and so on to traverse the string.

  

Or use an underscore method

  

For character sequences of strings, you can use chained calls to get the results you want, in the following example, the filter method is used for the original string to generate a new string (minus all the characters L), and then the map method is called to convert the newly generated string to uppercase.

  

Using the For loop and yield can also achieve the effect of the map method

  

The map method, the for and yield methods can convert the old collection into a new collection, while the Foreach method operates on each element of the collection without generating new results.

  3. Discussion

Since Scala treats strings as a sequence of characters, and Scala is an object-oriented and functional programming language, in Java, you can use the following methods to iterate through each character in a string

String s = "Hello" for (int i = 0; i < s.length (); i++) {    char c = S.charat ( i);    System.out.println (c);    }

  Understand the working mechanism of the Map method

In the map method, you can pass in a large chunk of code

  

The above function is to change the character of a string from uppercase to lowercase, because it is the string's map method called, so that only one character of the string is processed at a time, map treats the string as a character-order collection, and the map method has an implicit loop in which only one character is passed in the loop at a time. In addition to passing the code block directly in the map method, you can define the function first and then pass it on to the map, which guarantees the simplicity of the code.

  

This method can also be used in the For loop and yield

  

In addition to using method methods, you can also use the function to accomplish the above operations

  

  2.6 Finding patterns in strings

  1. Description of the problem

You need to determine if the string contains a regular expression pattern.

  2. Solution

Create a Regex object through the. R method of string, and then use the Findallin method when finding the first match, using the Findfirstin method, and finding all matches.

  

For the Findallin method, the result can be converted to an array, List, seq, etc.

  

  3. Discussion

The. R method that uses the string is the simplest way to create a Regex object, and the other way is to import the Regex class, create a Regex instance, and then use the method of the instance

  

  Handling the results returned by Findfirstin

Findfirstin finds the first match and returns a option[string]

The Option/some/none type will be discussed in a later section, and it is easy to assume that option is a container that either holds 0 or a value, and, for Findfirstin, returns Some ("123") when unsuccessful, returning none when unsuccessful

  

A method that returns a type of option[string] either returns some (String) or none

For the option type, to get its value, you can use the following method

· Getorelse

· Using the Foreach

· Using matching expressions

Using the Getorelse method, you can try to get a value or define a default value if it fails

  

Use the Foreach method as follows

  

Use the match expression method as follows

  

  2.7 Substitution mode for strings

  1. Description of the problem

You need to search the string for the regular expression pattern and replace them.

  2. Solution

Because the string is immutable, you cannot find and replace it directly on the string, but you can create a new string that contains the replacement, and you can use the ReplaceAll method to remember to assign the result to a value

  

You can also create a regular expression and then call the Replaceallin method, and also remember to assign the result to a new string

  

You can also call Replacefirstin to replace the first matching value, and remember to assign the result to a new string

  

  2.8 Extracting pattern-matching string parts

 1. Description of the problem

You need to extract one or more portions of a string that match the regular up expression.

  2. Solution

First define the extracted regular expression patterns, and then place them in parentheses to form a regular expression group

  

The example above extracts the numeric and alphabetic parts from the specified string and assigns values to count and fruit, respectively.

  3. Discussion

The syntax for the above example might be a bit odd, as if the pattern was defined two times as a Val field, but this syntax is very handy and readable, just imagine you're writing a search engine, you want people to search for movies in a variety of phrases, and you can have them enter any of these phrases to get a list of movies.

  

You can define a series of regular expressions to match, such as

// Match "Movies 80301"val movieszipre = "Movies (\\d{5})". R/  match "movies near Boulder, CO "val moviesnearcitystatere =" movies near ([a-z]+), ([A-z]{2}) ". R

After that, you can match the user's input, and then get the search results, pseudo-code is as follows

textusertyped Match { case movieszipre (Zip) = getsearchresults (Zip) case Moviesnearcitystatere (city, state) = Getsearchresults (city, State) Case _ = = println ("did not Match a Regex ")}

The preceding regular expression can match the following string

  

When matching, you need to consider all the circumstances, such as case _ indicates that it cannot match, the following string will not match

  

  2.9 Characters to access strings

  1. Description of the problem

You want to get the characters in a particular position in the string.

  2. Solution

You can use the Java Charat method

  

In addition, a better approach is the array notation

  

  3. Discussion

When the map method and foreach do not apply, you can consider string as an array type and then use array notation to access the characters, and the array notation in Scala differs from the Java array notation, because in Scala, array notation is a method call.

  

The Apply method is actually called when the array notation is called, but because of the presence of the Scala syntax sugar, the specified character can be obtained directly using the array notation.

  2.10 Adding a custom method to the String class

  1. Description of the problem

You want to add a custom method to the string class, such as "HAL". Increment, rather than using the increment method of the tool class StringUtilities.

  2. Solution

You can define an implicit class, and then define the method you want to add in the class

  

The actual encoding is slightly more complicated because the implicit class needs to be defined in the scope of the method that can be defined, which means that the implicit class must be defined in class, object, and package object.

 Package com.leesf.utilsobject stringutils {    class  stringimprovements (val s:string) {        = S.map (c = (c + 1). ToChar)    }}    

When in use, you need to import com.leesf.utils.StringUtils

 Package Foo.bar Import  extends  App {    println ("HAL". Increment)}

You can also put an implicit class in a package object

 Package COM.LEESF  Package object Utils {    class  stringimprovements (val s:string) {        = s.map (c = = (c + 1). T Ochar)    }}    

When in use, you need to import com.leesf.utils

 Package Foo.bar Import  extends  App {    println ("HAL". Increment)}

For pre-Scala2.10 versions, there is a slight difference from the above approach, where you first need to define the increment method in a common class

class stringimprovements (Val s:string) {    = S.map (c + = (c + 1). ToChar)}

Then define an implicit method for conversion

New Stringimprovements (s)

  3. Discussion

In Scala, you can add new methods to enclosing classes through implicit conversions, and import them when they are used, without inheriting the class to add methods (some final classes simply cannot inherit).

Iii. Summary

This blog post explains the string knowledge points in Scala, which is also a very high-frequency knowledge point in Scala programming, which has been combed, deepened the impression, and thank you all for watching the Garden friends ~

"Scala" Scala's string

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.