How does this Play 2 ScalaTemplates code work - scala

Please explain the code below:
#title(text: String) = #{
text.split(' ').map(_.capitalize).mkString(" ")
}
<h1>#title("hello world")</h1>

A breakdown of the reusable code block #title(text: String)
text.split( ' ' ) separates the text into a List by splitting the string by ' ', e.g. "hello world" would become ["hello", "world"]
map(_.capitalize) iterates the List, calls capitalize on each element, and returns the new List, e.g. ["hello", "world"] becomes ["Hello", "World"]. This blog post give a good overview of _.
mkString(" ") converts the List back to a String by joining the string with " ", e.g. ["Hello", "World"] becomes "Hello World"
In summary, #title(text: String) capitalizes all words in a String.
The <h1>#title("hello world")</h1> is how you could ouput the result in a ScalaTemplate.

Related

How to lowecase only first word in the sentence? [duplicate]

This question already has answers here:
Swift apply .uppercaseString to only the first letter of a string
(31 answers)
Closed last year.
I have a text "Hello Word" "Word Hello",
How can i get "hello Word" "word Hello" (for example)
'''
let string1 = "Hello Word"
let referenceString1 = "hello Word"
let string2 = "Word Hello"
let referenceString2 = "word Hello"
'''
Get first letter of the first word and make it lowercase , then remove first letter and add the rest.
extension StringProtocol {
var lowerCaseFirts: String { prefix(1).lowercased() + dropFirst() }
}
let str = "Hello World"
print(str.lowerCaseFirts)
def fun(sentence : str) -> str:
words = sentence.split()
if not (words[0])[0].islower():
words[0] = (words[0])[0].lower() + (words[0])[1:]
out = " ".join(words)
return out
if __name__ == '__main__':
sentence1 = "Hello Everyone"
out1 = fun(sentence1)
print(sentence1, " : ", out1)
sentence2 = "HOW ARE YOU"
out2 = fun(sentence2)
print(sentence2, " : ", out2)
Output:
Hello Everyone : hello Everyone
HOW ARE YOU : hOW ARE YOU
The selected answer works perfectly for the OPs use case:
Hello Word
However, if we are speaking about first word in a sentence, there could be a more complex string with multiple sentences:
Hello Word. JELLO world? WEllo Word.\n ZEllo world! MeLLow lord.
In such a case, using REGEX might also work to solve both the scenarios.
Someone with more savvy REGEX skills might be able to improve the REGEX
extension String
{
func withLowerCaseSentences() -> String
{
do
{
// A sentence is something that starts after a period, question mark,
// exclamation followed by a space. This is only not true for the first
// sentence
//
// REGEX to capture this
// (?:^|(?:[.!?]\\s+))
// Exclude group to get the starting character OR
// anything after a period, exclamation, question mark followed by a
// whitespace (space or optional new line)
//
// ([A-Z])
// Capture group to capture all the capital characters
let regexString = "(?:^|(?:[.!?]\\s+))([A-Z])"
// Initialize the regex
let regex = try NSRegularExpression(pattern: regexString,
options: .caseInsensitive)
// Convert string to a character array
var characters = Array(self)
// Loop through all the regex matches
for match in regex.matches(in: self,
options: NSRegularExpression.MatchingOptions(),
range: NSRange(location: 0,
length: count))
as [NSTextCheckingResult]
{
// We are not looking for the match, but for the group
// For example Hello Word. JELLO word will give give us two matches
// "H" and ". J" but each of the groups within each match
// will give us what we want which is "H" and "J" so we check if we
// have a group. Look up matches and groups to learn more
if match.numberOfRanges > 1
{
// Get the range (location and length) of first group from
// the regex match
let matchedRange = match.range(at: 1)
// Get the capital character at the start of the sentence we found
let characterToReplace = characters[matchedRange.location]
// Replace the capital letter with a lower cased latter
characters[matchedRange.location]
= Character(characterToReplace.lowercased())
}
}
// Convert the processed character array back to a string if needed
return String(characters)
}
catch
{
// handle errors
print("error")
return self
}
}
}
Then it can be used:
let simpleString = "Hello world"
print("BEFORE")
print(simpleString)
print("\nAFTER")
print(simpleString.withLowerCaseSentences())
let complexString
= "Hello Word. JELLO world? WEllo Word.\n ZEllo world! MeLLow lord."
print("\nBEFORE")
print(complexString)
print("\nAFTER")
print(complexString.withLowerCaseSentences())
This gives the output:
BEFORE
Hello world
AFTER
hello world
BEFORE
Hello Word. JELLO world? WEllo Word.
ZEllo world! MeLLow lord.
AFTER
hello Word. jELLO world? wEllo Word.
zEllo world! meLLow lord.

Print in Swift 3

i would like to know what's the different between these two way to print the object in Swift.
The result seems identical.
var myName : String = "yohoo"
print ("My name is \(myName).")
print ("My name is ", myName, ".")
There is almost no functional difference, the comma simply inputs a space either before or after the string.
let name = "John"
// both print "Hello John"
print("Hello", name)
print("Hello \(name)")
You can use the \(variable) syntax to create interpolated strings, which are then printed just as you input them. However, the print(var1,var2) syntax has some "facilities":
It automatically adds a space in between each two variables, and that is called separator
You can customise your separator based on the context, for example:
var hello = "Hello"
var world = "World!"
print(hello,world,separator: "|") // prints "Hello|World!"
print(hello,world,separator: "\\//") // prints "Hello\\//World!"
No difference between the two
var favoriteFood: String = "Pizza" //favoriteFood = Pizza
//both print the same thing
print("My favorite food is", favoriteFood)
print("My favorite food is \(favoriteFood)")

swift why is characters.split used for? and why is map(String.init) used for

import Foundation
for i in 1 ... n {
let entry = readLine()!.characters.split(" ").map(String.init)
let name = entry[0]
let phone = Int(entry[1])!
phoneBook[name] = phone``
}
//can someone explain this piece of code`
I assume you know everything else in the code except this line:
let entry = readLine()!.characters.split(" ").map(String.init)
readLine() reads user input and returns it. Let's say the user input is
Sweeper 12345678
using .characters.split(" "), we split the input using a separator. What is this separator? A space (" ")! Now the input has been split into two - "Sweeper" and "12345678".
We want the two split parts to be strings, right? Strings are much more easier to manipulate. Currently the split parts are stored in an array of String.CharacterView.SubSequence. We want to turn each String.CharacterView.SubSequence into a string. That is why we use map. map applies a certain function to everything in a collection. So
.map(String.init)
is like
// this is for demonstration purposes only, not real code
for x in readLine()!.characters.split(" ") {
String.init(x)
}
We have now transformed the whole collection into strings!
There is error in your code replace it like below:
let entry = readLine()!.characters.split(separator: " ").map(String.init)
Alternative to the above code is:
let entry = readLine()!.components(separatedBy: " ")
Example:
var str = "Hello, playground"
let entry = str.characters.split(separator: " ").map(String.init)
print(entry)
Now characters.split with split the characters with the separator you give in above case " "(space). So it will generate an array of characters. And you need to use it as string so you are mapping characters into String type by map().

Print String using variadic params without comma, newline and brackets in Swift

While I was trying to use Swift's String(format: format, args) method, I found out that I cannot print the formatted string directly without newline(\n) and brackets being added.
So for example, I have a code like this:
func someFunc(string: String...) {
print(String(format: "test %#", string))
}
let string = "string1"
someFunc(string, "string2")
the result would be:
"test (\n string1,\n string2\n)\n"
However, I intend to deliver the result like this:
"test string1 string2"
How can I make the brackets and \n not being printed?
Since string parameter is a sequence, you can use joinWithSeparator on it, like this:
func someFunc(string: String...) {
print(string.joinWithSeparator(" "))
}
someFunc("quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog")
You will first need to concatenate your list of input strings, otherwise it will print as a list, hence the commas and parentheses. You can additionally strip out the newline characters and whitespace from the ends of the string using a character set.
var stringConcat : String = ''
for stringEntry in string {
stringConcat += stringEntry.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
Then just print out the stringConcat.

how to use separator param of print in swift2

Sorry for newbee question.
I really do not know how to use separator param in print
var str = "Hello, playground"
var strs = ["abc","def"]
print(str)
print(strs, separator: ",", terminator: "")
print(str, separator: ",", terminator: "\n")
print accepts its arguments separately, so you can do this:
print("abc", "def", separator: ",")
But you have an array of strings, so you should do this:
print(strs.joinWithSeparator(","))
print ("rob" ,"mark" , "hanna" , separator:"$") // prints rob$mark$hanna
To use separator we need to pass multiple string inside print function.