Truncate String with Ellipsis
Truncate a string to a maximum length and append "..." if it was shortened — useful for list titles in mobile UIs.
Sample input
"Hello World", maxLen = 8
Sample output
Hello Wo...
Solution
s = "Hello World"
max_len = 8
print(s if len(s) <= max_len else s[:max_len] + "...")
const s = "Hello World";
const maxLen = 8;
console.log(s.length <= maxLen ? s : s.slice(0, maxLen) + "...");
public class Main {
public static void main(String[] args) {
String s = "Hello World";
int maxLen = 8;
System.out.println(s.length() <= maxLen ? s : s.substring(0, maxLen) + "...");
}
}
fun main() {
val s = "Hello World"
val maxLen = 8
println(if (s.length <= maxLen) s else s.substring(0, maxLen) + "...")
}
let s = "Hello World"
let maxLen = 8
if s.count <= maxLen {
print(s)
} else {
print(String(s.prefix(maxLen)) + "...")
}
void main() {
String s = 'Hello World';
int maxLen = 8;
print(s.length <= maxLen ? s : s.substring(0, maxLen) + '...');
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
int maxLen = 8;
if ((int) s.size() <= maxLen) {
cout << s << endl;
} else {
cout << s.substr(0, maxLen) << "..." << endl;
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Hello World";
int maxLen = 8;
if ((int) strlen(s) <= maxLen) {
printf("%s\n", s);
} else {
printf("%.*s...\n", maxLen, s);
}
return 0;
}