有一字符串,包含n個字符。寫一函數,將此字符串中從第m個字符開始的全部字符復制成為另一個字符串。
解題思路: 當字符串指針移動到源字符串的第m位時,則開始向另一個緩沖區中寫入剩下的數據
答案:
#include <stdio.h>
#include <string.h>
int main()
{
char buf1[1024], buf2[1024];
printf("Please enter a string: ");
scanf_s("%s", buf1, 1024);
int m;
printf("Please enter a location to start copying: ");
scanf_s("%d", &m);
if (m < 0 || m > strlen(buf1)) {//檢測輸入的位置是否合法
printf("Illegal location entered\n");
return -1;
}
char *ptr1 = buf1 + m; // 從第m個位置開始復制新數據
char *ptr2 = buf2;
while (*ptr1 != '\0') {
*ptr2++ = *ptr1++;
}
*ptr2 = '\0';//不要忘了字符串結尾標志
printf("%s\n", buf2);
system("pause");
return 0;
}