Truncate String

Easy~10 min

Given a string s and a maximum length maxLength, truncate the string if it exceeds the maximum length.

  • If s.length > maxLength, return the first maxLength characters of s followed by "..."
  • If s.length <= maxLength, return s unchanged

Note: The "..." is appended after the truncated string, so the total returned length will be maxLength + 3 when truncation occurs.

Examples

Example 1
Input: s = "Hello, World!", maxLength = 5
Output: "Hello..."
Explanation: The string has 13 characters which exceeds 5, so we take the first 5 characters and add "...".
Example 2
Input: s = "Hi", maxLength = 5
Output: "Hi"
Explanation: The string has 2 characters which does not exceed 5, so we return it as-is.
Example 3
Input: s = "abcdef", maxLength = 6
Output: "abcdef"
Explanation: The string length equals maxLength exactly, so no truncation is needed.

Constraints

  • 0 <= s.length <= 10^4
  • 1 <= maxLength <= 10^4
  • s contains printable ASCII characters
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run