自行設計函數實現字符串復制


【問題描述】
字符串復制。
輸入一個字符串t和一個正整數m,將字符串t中從第m個字符開始的全部字符復制到字符串s中,再輸出字符串s。
要求用字符指針定義並調用函數strmcpy(s,t,m),它的功能是將字符串t中從第m個字符開始的全部字符復制到字符串s中。

【輸入形式】
首先打印提示"Input a string:";然后直接在冒號后面輸入字符串,作為t的內容,字符串中可以包含空格;字符串以回車結束。
打印提示"Input an integer:";然后直接在冒號后面輸入一個正整數,代表m的值;回車。

【輸出形式】
首先打印"Output is:";緊跟后面輸出字符串s中的內容;換行。

【運行時的輸入輸出樣例】
Input a string:happy new year
Input an integer:7
Output is:new year

【提示】
第4組測試數據,當輸入的整數m為0,不是合法的正整數時,輸出0

#include <iostream>
#include <string.h>
using namespace std;

void strmcpy(char * s, char *t, int m);

int main()
{
    char s[100],t[100];
    int m;
    cout << "Input a string:";
    cin.get(t,100);
    cin.get();
    cout << "Input an integer:";
    cin  >> m;
    if(m>0)
    {
        strmcpy(s,t,m);
        cout << "Output is:" << s << endl;
    }
    else cout << "Output is:0" << endl;
    return 0;
}

void strmcpy(char * s, char *t, int m)
{
    int i,len = strlen(t)-m+1;//len是剩下要復制字符串的長度
    for(i=0;i<len;++i,++m)
        s[i] = t[m-1];
    s[i] = '\0';//別忘記在末尾添加上結束標記符
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM