Suppose there are 3 strings:
protein, starch, drink
Concatenating those, we could say what is for dinner:
Example:
val protein = "fish" val starch = "chips" val drink = "wine" val dinner = protein + ", " + starch + ", " + drink
But what if something was missing, for example the protein, because my wife couldn't catch anything. Then, we will have: ,chips, drink
for dinner.
There is a slick way to concatenate the strings to optionally add the commas - I just don't know what it is ;-). Does anyone have a nice idea?
I'm looking for something like:
val dinner = protein +[add a comma if protein is not lenth of zero] + starch .....
It's just a fun exercise I'm doing, so now sweat if it can't be done in some cool way. The reason that I'm trying to do the conditional concatenation in a single assignment, is because I'm using this type of thing a lot in XML and a nice solution will make things..... nicer.
Description. The strcat() function concatenates string2 to string1 and ends the resulting string with the null character. The strcat() function operates on null-ended strings.
The strcat() function returns a pointer to the concatenated string ( string1 ).
Concatenation is the process of combining two or more strings to form a new string by subsequently appending the next string to the end of the previous strings. In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.
When you say "it may be absent", this entity's type should be Option[T]
. Then,
def dinner(components: List[Option[String]]) = components.flatten mkString ", "
You would invoke it like this:
scala> dinner(None :: Some("chips") :: Some("wine") :: Nil) res0: String = chips, wine
In case you absolutely want checking a string's emptiness,
def dinner(strings: List[String]) = strings filter {_.nonEmpty} mkString ", " scala> dinner("" :: "chips" :: "wine" :: Nil) res1: String = chips, wine
You're looking for mkString on collections, maybe.
val protein = "fish" val starch = "chips" val drink = "wine" val complete = List (protein, starch, drink) val partly = List (protein, starch) complete.mkString (", ") partly.mkString (", ")
results in:
res47: String = fish, chips, wine res48: String = fish, chips
You may even specify a start and end:
scala> partly.mkString ("<<", ", ", ">>") res49: String = <<fish, chips>>
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