6-7 移动字母 (10 point(s))

By | 最新修改:2024-08-17

这是 拼题A(PTA)《中M2019秋C入门和进阶练习集》的习题。原题在https://pintia.cn/problem-sets/1163286449659043840/problems/1174288506294865926 (侵删)
本人的答案仅供交流学习,请勿用于当作答案来提交!

题目描述:

6-7 移动字母 (10 point(s))
本题要求编写函数,将输入字符串的前3个字符移到最后。

函数接口定义:

void Shift( char s[] );

其中char s[]是用户传入的字符串,题目保证其长度不小于3;函数Shift须将按照要求变换后的字符串仍然存在s[]里。

裁判测试程序样例:

#include <stdio.h>
#include <string.h>

#define MAXS 10

void Shift( char s[] );

void GetString( char s[] ); // 实现细节在此不表

int main()
{
    char s[MAXS];

    GetString(s);
    Shift(s);
    printf("%s\n", s);

    return 0; 
}
// 你的代码将被嵌在这里

输入样例:
abcdef
输出样例:
defabc

我的答案:

/*================================================================
*   Copyright (C) 2019 程序知路. All rights reserved.
*   
*   Filename    :6-7-移动字母.c
*   Author      :程序知路
*   E-Mail      :admin@icxzl.com
*   Create Date :2019年09月26日
*   Description :
================================================================*/
#include <stdio.h>
#include <string.h>

#define MAXS 10

void Shift( char s[] );

int main()
{
    char s[MAXS] = "abcefg";

    Shift(s);
    printf("%s\n", s);

    return 0; 
}

// 以下代码是有效代码
void Shift( char s[] ) {

    if (strlen(s) >= 3) {
        char ps[4];

        size_t i;
        for (i = 0; i < 3; i ++)
            ps[i] = s[i];
        ps[i] = '\0';
        for (i = 0; i < strlen(s) - 3;i ++)
            s[i] = s[i + 3];

        s[i] = ps[0];
        s[i + 1] = ps[1];
        s[i + 2] = ps[2];
        s[i + 3] = '\0';
    }
}

程序知路

鉴于本人的相关知识储备以及能力有限,本博客的观点和描述如有错漏或是有考虑不周到的地方还请多多包涵,欢迎互相探讨,一起学习,共同进步。

本文章可以转载,但是需要说明来源出处!

本文使用的部分图片来源于网上,若是侵权,请与本文作者联系删除: admin@icxzl.com