Way Too Long Words (71A) is a gentle introduction to reading several strings in a loop and working with their length. It is also a nice reminder of where abbreviations like i18n (internationalization) and l10n (localization) come from, since that is exactly the rule this problem asks you to implement.
The problem in short
You get n words (1 ≤ n ≤ 100), each made of lowercase letters and at most 100 characters long. A word is “too long” if it has more than 10 characters. Too-long words must be printed as: the first letter, then the number of letters between the first and last, then the last letter. Shorter words are printed unchanged.
Full statement: Codeforces 71A – Way Too Long Words.
Approach
- Read n.
- For each word, find its length len with
strlen. - If len > 10, print
word[0], then len − 2, thenword[len - 1]. - Otherwise print the word as it is.
The number in the middle is len − 2 because we exclude the first and last characters.
Example
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
“word” has 4 letters, so it stays. “localization” has 12 letters: first l, last n, 10 in between, giving l10n. In the same way “internationalization” (20 letters) becomes i18n and the 45-letter lung disease becomes p43s.
Solution in C
#include <stdio.h>
#include <string.h>
int main(void) {
int n;
char word[105];
scanf("%d", &n);
while (n--) {
scanf("%s", word);
int len = strlen(word);
if (len > 10)
printf("%c%d%c\n", word[0], len - 2, word[len - 1]);
else
printf("%s\n", word);
}
return 0;
}
A printf with %c%d%c builds the abbreviation in one line, so there is no need to construct a new string.
Complexity
Each character is read once and strlen walks each word once, so the total time is O(total length of all words), at most about 10,000 characters. Memory is one buffer of 105 characters.
Common mistakes
- Using
>= 10instead of> 10. A word of exactly 10 letters must not be abbreviated. - Making the buffer exactly 100 bytes. A 100-letter word needs 101 bytes because of the terminating
'\0'. I use 105 to be safe. - Writing
scanf("%s", &word). An array name is already a pointer, so drop the&. It happens to work on most compilers, but it is technically the wrong type.
Practice next
Next string problems in the same spirit: 118A String Task and 112A Petya and Strings.
good bro
ReplyDelete