#K82342. Truncate String to N Words
Truncate String to N Words
Truncate String to N Words
You are given a string s
which may contain extra spaces, and an integer n
. Your task is to truncate the string to its first n
words.
Definition: A word is defined as a maximal sequence of non-space characters. Any extra spaces should be ignored during processing.
If the string contains fewer than n
words, output the string as is.
Example:
- Input: "The quick brown fox jumps over the lazy dog", n = 4; Output: "The quick brown fox".
Note: The output should not have leading or trailing spaces, and words should be separated by a single space.
inputFormat
The input is read from stdin and consists of two lines:
- The first line contains the string
s
. It may contain spaces. - The second line contains an integer
n
indicating the number of words to keep.
outputFormat
Output to stdout a single line: the truncated version of the string, containing at most the first n
words delimited by a single space.
The quick brown fox jumps over the lazy dog
4
The quick brown fox