If I have the phrase "New York City" how do I get the first letter of each word? My googling has only shown me how to capitalize the first letter in each word, which is seemingly different from what I'm trying to do.
Given my limited knowledge of Scala, I could probably do this procedurally but I was hoping someone could shed some Scala knowledge on me and show me an example that depicts a functional approach to this problem.
To get the first letter of each word in a string: Call the split() method on the string to get an array containing the words in the string. Call the map() method to iterate over the array and return the first letter of each word. Join the array of first letters into a string, using the join() method.
str[1] gives you the second character in str . In your code you defined initial as a pointer set to the address of that second character. You then treated initial as a string (by printing it with the %s specifier) so you got the second character and everything after it, up to the \0 character at the end of the string.
All other versions work fine but in order to avoid failure with badly formatted strings (two blanks in a row, empty string), use
"New York City".split(" ").flatMap(_.headOption).mkString
which also works for
"New York City".split(" ").flatMap(_.headOption).mkString
or even
"".split(" ").flatMap(_.headOption).mkString
As suggested by dhg, one may want to use a more appropriate regex such as "\\s+"
as well. But then one might just as well use something even more appropriate:
"""\w+""".r.findAllIn("New York City").map(_.head).mkString
(In here the /\w+/
should hopefully spare us from pathological cases so we can go with the .head
version.)
scala> "New York City".split(" ").map(_.head).mkString
res5: String = NYC
This splits by " " into an Array of words. Then we map over that array and call String.head which gets the first character.
"New York City".split(" ").toList.map(_(0))
gives the characters:
List[Char] = List(N, Y, C)
If you want a string use mkString
on the List[Char]
:
"New York City".split(" ").toList.map(_(0)) mkString
to get:
String = NYC
"New York City".split(" ").map(_.charAt(0))
Will give you a char array
Here's an alternative to using split (Regex).
The trick here is to use zip to allow testing of the current and previous character in the same iteration as you traverse the String, word boundaries consist of any letter preceded by a non-letter.
The two special cases, first and last letter, are handled by 1) prepending a space to a copy of the String which also sets up the 1 character skew required for the zip and 2) zip truncates partial pairs.
val s = "\n1New\n\t \t \tYork --City\n\t"
def firstLetters(s: String) = {
" "+s zip s collect {case (w, c) if ! w.isLetter && c.isLetter => c}
}
firstLetters(s)
returns
Vector(N, Y, C)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With