題目相關
題目鏈接
AtCoder Beginner Contest 168 B題,https://atcoder.jp/contests/abc168/tasks/abc168_b。
Problem Statement
We have a string S consisting of lowercase English letters.
If the length of S is at most K, print SS without change.
If the length of S exceeds K, extract the first K characters in S, append ...
to the end of them, and print the result.
Input
Input is given from Standard Input in the following format:
K
S
Output
Print a string as stated in Problem Statement.
Samples1
Sample Input 1
7
nikoandsolstice
Sample Output 1
nikoand...
Explaination
nikoandsolstice
has a length of 15, which exceeds K=7.
We should extract the first 7 characters in this string, append ...
to the end of them, and print the result nikoand...
.
Samples2
Sample Input 2
40
ferelibenterhominesidquodvoluntcredunt
Sample Output 2
ferelibenterhominesidquodvoluntcredunt
Constraints
- K is an integer between 1 and 100 (inclusive).
- S is a string consisting of lowercase English letters.
- The length of S is between 1 and 100 (inclusive).
題解報告
本題含義
給一個數字 K,一個字符串 S。如果字符串 S 的長度小於 K,輸出本身。如果字符串 S 的長度大於 K,輸出前 K 個字符,後面加上 3 個點。
樣例數據分析
本題是一個水題,我寫這個報告,也只是水一下。所以不需要樣例數據分析了。
數據範圍分析
K 的最大值是 100,字符串 S 的最大長度爲 100。
算法設計
一道非常簡單的入門級模擬題。
本題可以使用 STL 的 string,也可以使用字符串數組。如果使用字符串數組,要注意長度的定義。100 是不夠的。爲什麼?假設 S 輸入長度爲 100 個字符,K 的大小爲 99,那麼最終實際的字符長度爲 99+3=102 個。
AC 參考代碼
#include <bits/stdc++.h>
using namespace std;
int main() {
int k;
char s[106];
cin>>k>>s;
if (strlen(s)>k) {
s[k]='.';
s[k+1]='.';
s[k+2]='.';
s[k+3]='\0';
}
cout << s << endl;
return 0;
}