-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path01_Strings.sc
241 lines (206 loc) · 6.19 KB
/
01_Strings.sc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"Hello, world".getClass.getName
val s = "Hello, world"
s.length
val s = "Hello" + " world"
"hello".foreach(println)
for (c <- "hello") println(c)
s.getBytes.foreach(println)
val result = "hello world".filter(_ != 'l')
"scala".drop(2).take(2).capitalize
// 1.1 Testing String Equality
val s1 = "Hello"
val s2 = "Hello"
val s3 = "H" + "ello"
s1 == s2
s1 == s3
val s4: String = null
s3 == s4
s4 == s3
val s1 = "Hello"
val s2 = "hello"
s1.toUpperCase == s2.toUpperCase
val s1: String = null
val s2: String = null
s1.toUpperCase == s2.toUpperCase
val a = "Marisa"
val b = "marisa"
a.equalsIgnoreCase(b)
// 1.2 Creating Multiline Strings
val foo = """This is
a multiline
String"""
val speech = """Four score and
|seven years ago""".stripMargin
val speech = """Four score and
#seven years ago""".stripMargin('#')
val speech = """Four score and
|seven years ago
|our fathers""".stripMargin.replaceAll("\n", " ")
val s = """This is known as a
|"multiline" string
|or 'heredoc' syntax.""".stripMargin.replaceAll("\n", " ")
// 1.3 Splitting Strings
"hello world".split(" ")
"hello world".split(" ").foreach(println)
val s = "eggs, milk, butter, Coco Puffs"
s.split(",")
s.split(",").map(_.trim)
"hello world, this is Al".split("\\s+")
"hello world".split(" ")
"hello world".split(' ')
// 1.4 Substituting Variables into Strings
val name = "Fred"
val age = 33
val weight = 200.00
println(s"$name is $age years old, and weighs $weight pounds.")
println(s"Age next year: ${age + 1}")
println(s"You are 33 years old: ${age == 33}")
case class Student(name: String, score: Int)
val hannah = Student("Hannah", 95)
println(s"${hannah.name} has a score of ${hannah.score}")
println(s"$hannah.name has a score of $hannah.score")
println(f"$name is $age years old, and weighs $weight%.2f pounds.")
println(f"$name is $age years old, and weighs $weight%.0f pounds.")
val out = f"$name, you weigh $weight%.0f pounds."
s"foo\nbar"
raw"foo\nbar"
val name = "Fred"
val age = 33
val s = "%s is %d years old".format(name, age)
println("%s is %d years old".format(name, age))
override def toString: String = "%s %s, age %d".format(firstName, lastName, age)
// 1.5 Processing a String One Character at a Time
val upper = "hello, world".map(c => c.toUpper)
val upper = "hello, world".map(_.toUpper)
val upper = "hello, world".filter(_ != 'l').map(_.toUpper)
for (c <- "hello") println(c)
val upper = for (c <- "hello, world") yield c.toUpper
val result = for {
c <- "hello, world" if c != 'l'
} yield c.toUpper
"hello".foreach(println)
String s = "Hello";
/*
* StringBuilder sb = new StringBuilder( ;
* for (int i = 0; i < s.length(); i++) {
* char c = s.charAt(i);
* // do something with the character ...
* // sb.append ...
* }
* String result = sb.toString();
*/
"HELLO".map(c => (c.toByte + 32).toChar)
"HELLO".map { c =>
(c.toByte + 32).toChar
}
def toLower(c: Char): Char = (c.toByte + 32).toChar
"HELLO".map(toLower)
val s = "HELLO"
for (c <- s) yield toLower(c)
package tests
/**
* Calculate the Adler-32 checksum using Scala.
* @see http://en.wikipedia.org/wiki/Adler-32
*/
object Adler32Checksum {
val MOD_ADLER = 65521
def main(args: Array[String]) {
val sum = adler32sum("Wikipedia")
printf("checksum (int) = %d\n", sum)
printf("checksum (hex) = %s\n", sum.toHexString)
}
def adler32sum(s: String): Int = {
var a = 1
var b = 0
s.getBytes.foreach { char =>
a = (char + a) % MOD_ADLER
b = (b + a) % MOD_ADLER
}
// note: Int is 32 bits, which this requires
b * 65536 + a // or (b << 16) + a }
}
}
"hello".getBytes
"hello".getBytes.foreach(println)
// 1.6 Finding Patterns in Strings
val numPattern = "[0-9]+".r
val address = "123 Main Street Suite 101"
val match1 = numPattern.findFirstIn(address)
val match2 = numPattern.findAllIn(address)
match2.foreach(println)
import scala.util.matching.Regex
val numPattern = new Regex("[0-9]+")
val address = "123 Main Street Suite 101"
val match1 = numPattern.findFirstIn(address)
match1 match {
case Some(s) => println(s"Found: $s")
case None =>
}
// 1.7 Replacing Patterns in Strings
val address = "123 Main Street".replaceAll("[0-9]", "x")
val regex = "[0-9]".r
val newAddress = regex.replaceAllIn("123 Main Street", "x")
val result = "123".replaceFirst("[0-9]", "x")
val regex = "H".r
val result = regex.replaceFirstIn("Hello world", "J")
// 1.8 Extracting Parts of a String That Match Patterns
val pattern = "([0-9]+) ([A-Za-z]+)".r
val pattern(count, fruit) = "100 Bananas"
// match "movies 80301"
val MoviesZipRE = "movies (\\d{5})".r
// match "movies near boulder, co"
val MoviesNearCityStateRE = "movies near ([a-z]+), ([a-z]{2})".r
textUserTyped match {
case MoviesZipRE(zip) => getSearchResults(zip)
case MoviesNearCityStateRE(city, state) => getSearchResults(city, state)
case _ => println("did not match a regex")
}
// 1.9 Accessing a Character in a String
"hello".charAt(0)
"hello" (0)
"hello" (1)
"hello".apply(1)
// 1.10 Add Your Own Methods to the String Class
implicit class StringImprovements(s: String) {
def increment = s.map(c => (c + 1).toChar)
}
"HAL".increment
package com.alvinalexander.utils
object StringUtils {
implicit class StringImprovements(val s: String) {
def increment = s.map(c => (c + 1).toChar)
}
}
package foo.bar
import com.alvinalexander.utils.StringUtils._
object Main extends App {
println("HAL".increment)
}
// package.scala
package com.alvinalexander
package object utils {
implicit class StringImprovements(val s: String) {
def increment = s.map(c => (c + 1).toChar)
}
}
package foo.bar
import com.alvinalexander.utils._
object MainDriver extends App {
println("HAL".increment)
}
implicit class StringImprovements(val s: String) {
// being explicit that each method returns a String
def increment: String = s.map(c => (c + 1).toChar)
def decrement: String = s.map(c => (c − 1).toChar)
def hideAll: String = s.replaceAll(".", "*")
}
implicit class StringImprovements(val s: String) {
def increment = s.map(c => (c + 1).toChar)
def decrement = s.map(c => (c - 1).toChar)
def hideAll: String = s.replaceAll(".", "*")
def plusOne = s.toInt + 1
def asBoolean = s match {
case "0" | "zero" | "" | " " => false
case _ => true
}
}