6-23 P字符串的復制 (5分)


6-23 P字符串的復制 (5分)
 

P字符串是另一種字符串實現形式。它也采用char數組來保存字符串中的字符,但是最后一個字符后面沒有結尾的'\0'。它使用另一個int類型的變量來表示字符串中的字符的個數。

本題要求編寫P字符串的復制和連接函數。

函數接口定義:

int pstr_cpy(char *s1, int len1, int size, const char *s2, int len2); int pstr_cat(char *s1, int len1, int size, const char *s2, int len2); 
 

pstr_cpy將s2字符串的內容復制到s1字符串,返回新的s1的長度。 pstr_cat將s2字符串的內容連接到s1字符串的后面,返回新的s1的長度。

參數中,size是s1的數組長度。

裁判測試程序樣例:

#include <stdio.h> const int SIZE = 80; // 這兩個函數由裁判程序提供 int pstr_scan(char* str, int size); void pstr_print(const char* str, int length); int pstr_cpy(char *s1, int len1, int size, const char *s2, int len2); int pstr_cat(char *s1, int len1, int size, const char *s2, int len2); int main() { char line[SIZE]; char text[SIZE/2]; int len1 = pstr_scan(line, SIZE); int len2 = pstr_scan(text, SIZE/2); len1 = pstr_cat(line, len1, SIZE, "\x0D\x0A", 2); len1 = pstr_cat(line, len1, SIZE, text, len2); len2 = pstr_cpy(text, len2, SIZE/2, line, len1); pstr_print(line, len1); pstr_print(text, len2); return 0; } /* 請在這里填寫答案 */ 
 

輸入樣例:

123A 123
 

輸出樣例:

123A
123123A
123



int pstr_cpy(char *s1, int len1, int size, const char *s2, int len2)
{
 int i;
 for(i=0;i<size&&i!=len2;i++)
 {
  s1[i]=s2[i];
 }
 return i;
}
int pstr_cat(char *s1, int len1, int size, const char *s2, int len2)
{
 int i;
 for(i=len1;i<size&&i<len1+len2;i++)
 {
  s1[i]=s2[i-len1];
 }
 return i;
}


免責聲明!

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



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