Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

kotlin - Concatenate 3 strings with separator

Write a function that concatenates three strings into one using a special separator. If the separator is not specified, it is a single space.

Suppose you have a standard input.

Concatenate the letters 1, 2, and 3. Insert a fourth input separator between the characters in 1-2-3.

However, if a specific keyword is entered, it will be output as a half-width space.

The following is my code.

import java.util.*

fun main() {
    val scanner = Scanner(System.`in`)
    val input = Array(4){scanner.next()}

    if (input[3] == "NO SEPARATOR"){
        println(" ")
    }else{
        input[3] == input[3]
    }
    println("$input[0]$input[3]$input[1]$input[3]$input[2]")
}
//Sample Input

abc
def
ghi
NO SEPARATOR

Sample Output

abc def ghi

I can't think of a solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, you should be reading based off lines, which means you don't need a scanner, you can use readLine. Secondly, you can use joinToString for adding a separator in between:

fun main() {
    val input = Array(3) { readLine()!! }
    var sep = readLine()!!
    if (sep == "NO SEPARATOR") {
        sep = " "
    }
    println(input.joinToString(sep))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...