1

Suppose we have a string "code". How would we concatenate any two characters? Say for example we need to concatenate last two characters,

str.init.last + str.last gives result as 201. How would we get de instead?

7
  • That's not concatenating, that's simply dropping the first two chars. Is that all you want to do? Commented Jan 11, 2017 at 6:29
  • 1
    Taking last two characters was just an example. Commented Jan 11, 2017 at 6:35
  • Then specify what exactly you want to do. If you're talking about general string fiddling, you can use indexes into the string. Commented Jan 11, 2017 at 6:36
  • 1
    My question in general was if we can concatenate characters? One possible way as @Michal has shown and as you have suggested is to use indexes and convert the result into a String! Another way, similarly, could be s"${str.init.last}${str.last}". I was wondering if characters can be concatenated without conversion to a String? Commented Jan 11, 2017 at 6:44
  • 1
    It depends on what is your goal. Char is in general a number representing character in ASCII table. Adding two Char values is in fact adding numbers. If you wish to produce String, you cannot use addition. Another way is to call .toString method on each char before addition but it makes code less readable. Commented Jan 11, 2017 at 6:58

2 Answers 2

6

You can use string interpolation to make any combination of characters:

scala> val code = "code" code: String = code scala> s"${code(1)}${code(3)}" res0: String = oe 
Sign up to request clarification or add additional context in comments.

Comments

0
"code".init.last.toString + "code".last.toString val res7: String = de 

(use toString first to convert char to String and then concatenate with +)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.