【PTA】L1-32 Left-pad (C++)

简介: 【PTA】L1-32 Left-pad (C++)

题目要求:

根据新浪微博上的消息,有一位开发者不满NPM(Node Package Manager)的做法,收回了自己的开源代码,其中包括一个叫left-pad的模块,就是这个模块把javascript里面的React/Babel干瘫痪了。这是个什么样的模块?就是在字符串前填充一些东西到一定的长度。例如用*去填充字符串GPLT,使之长度为10,调用left-pad的结果就应该是******GPLT。Node社区曾经对left-pad紧急发布了一个替代,被严重吐槽。下面就请你来实现一下这个模块。

输入格式:

输入在第一行给出一个正整数N(≤104)和一个字符,分别是填充结果字符串的长度和用于填充的字符,中间以1个空格分开。第二行给出原始的非空字符串,以回车结束。

输出格式:

在一行中输出结果字符串。

输入样例1:

15 _
I love GPLT

输出样例1:

____I love GPLT

输入样例2:

4 *
this is a sample for cut

输出样例2:

cut

思路:

1.先输入n的个数、字符、字符串

2.进行判断,如果n的值小于字符串的长度,则取出字符串后n位

3.如果n的值大于字符串的长度,则先输出n-字符串的长度,然后输出字符串

注意:(1)输入完第一行输入第二行的字符串的时候要中间加一个getchar()来吸收回车字符

代码:

#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    int n;
    char c; 
    string s;
    cin >> n >> c;
    getchar();
    getline(cin,s);
    if(n < s.size())
    {
        for(int i = s.size() - n; i <= s.size(); i ++)
        {
            cout << s[i];
        }
    }
    else 
    {
        int t = n - s.size();
        for(int j = 0; j < t; j ++)
        {
            cout << c;
        }
        for(int i = 0; i <= s.size(); i ++)
        {
            cout << s[i];
        }
        
    }
    cout << endl;
    return 0;
}

测试用例:


目录
相关文章
|
2月前
|
算法
二分查找及模板深度解析:right <= left 还是 right < left ? mid=left+(right-left)/2还是mid=left+(right-left +1 )/2 ?
二分查找及模板深度解析:right <= left 还是 right < left ? mid=left+(right-left)/2还是mid=left+(right-left +1 )/2 ?
29 0
|
24天前
|
前端开发 JavaScript 开发者
L1-032 Left-pad
L1-032 Left-pad
19 1
LeetCode 404. Sum of Left Leaves
计算给定二叉树的所有左叶子之和。
57 0
LeetCode 404. Sum of Left Leaves
|
机器学习/深度学习 Windows
Codeforces Round #748 (Div. 3) F - Red-Black Number (记忆化搜索)
Codeforces Round #748 (Div. 3) F - Red-Black Number (记忆化搜索)
78 0
AtCoder Beginner Contest 222 E - Red and Blue Tree(dfs dp)
AtCoder Beginner Contest 222 E - Red and Blue Tree(dfs dp)
92 0
codeforces1244——D.Paint the Tree(dfs)
codeforces1244——D.Paint the Tree(dfs)
57 0
|
人工智能
Rem of Sum is Num——UPC
题目描述 Given are a sequence of N positive integers A1,A2,…,AN, and a positive integer K. Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements.
93 0
|
Java
HDOJ 1420 Prepared for New Acmer(DP)
HDOJ 1420 Prepared for New Acmer(DP)
68 0
【PTA】7-6 求最大公约数 (40point(s))
【PTA】7-6 求最大公约数 (40point(s))
167 0