---
# System prepended metadata

title: 1816. Truncate Sentence
tags: [Leetcode, Easy]

---

# 1816. Truncate Sentence
###### tags: `Leetcode` `Easy`
Link: https://leetcode.com/problems/truncate-sentence/description/
## Code
With Split
```java=
class Solution {
    public String truncateSentence(String s, int k) {
        String[] splited = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<k; i++){
            if(i!=0) sb.append(" ");
            sb.append(splited[i]);
        }
        return sb.toString();
    }
}
```
Without Split
```java=
class Solution {
    public String truncateSentence(String s, int k) {
        int idx = 0, spaceCnt = 0;
        while(idx<s.length() && spaceCnt<k){
            if(s.charAt(idx)==' ') spaceCnt++;
            idx++;
        }
        return spaceCnt==k?s.substring(0, idx-1):s;
    }
}
```