# 1816. Truncate Sentence ## 題目概要 給定一個字串(句子),並給定一個正整數 k,將字串中的前 k 個單字輸出。 ``` Example 1: Input: s = "Hello how are you Contestant", k = 4 Output: "Hello how are you" Explanation: The words in s are ["Hello", "how" "are", "you", "Contestant"]. The first 4 words are ["Hello", "how", "are", "you"]. Hence, you should return "Hello how are you". Example 2: Input: s = "What is the solution to this problem", k = 4 Output: "What is the solution" Explanation: The words in s are ["What", "is" "the", "solution", "to", "this", "problem"]. The first 4 words are ["What", "is", "the", "solution"]. Hence, you should return "What is the solution". Example 3: Input: s = "chopper is not a tanuki", k = 5 Output: "chopper is not a tanuki" ``` ## 解題技巧 - 用 `splice` 來解,第一個參數為插入或刪除的索引位置,第二個參數為要刪除的元素數量,第三個參數為要插入的元素內容。這邊我們只是用 splice 來獲取前 k 個單字而已。 ## 程式碼 ```javascript= /** * @param {string} s * @param {number} k * @return {string} */ var truncateSentence = function(s, k) { return s.split(' ').splice(0, k, '').join(' '); }; ``` ![](https://i.imgur.com/7erN7XD.png)