小学四年级英语课外:帮帮我吧——编程题

来源:百度文库 编辑:高校问答 时间:2024/04/29 08:40:23
编写一程序,将字符串中的第m个字符开始的全部字符复制成另一个字符串.要求在主函数中输入字符串及m的值并输出复制结果,在被调用函数中完成复制.试编程.
c语言编

#include <stdio.h>
#include <malloc.h>

//函数作用: 返回参数src中由参数pos指定位置开始的子串的副本。
//函数参数: src 原始字符串 pos 指定子串的开始位置
//约束条件:
//返回值: 当pos<0或者src为空时返回NULL
// 当pos的值大于src的长度的时候返回新的空串\0
// 其它情况返回指定子串的副本
char *subString(char *src, int pos)
{
char *p;
char *result;
char *temp;
int i;
int length;

//若pos小于0,或者src是NULL,则返回NULL
if (pos<0 || src==NULL) {
return NULL;
}

//找到子串的开始位置
p = src;
for (i=0; i<pos; i++) {
if (p == '\0') { //如果pos长于原始字符串,则返回空串
result = (char *)malloc(1 * sizeof(char));
*result = '\0';
return result;
}
p++;
}

//得到子串的长度
length = 0;
temp = p;
while (*temp != '\0') {
temp++;
length++;
}
length = length + 1; //加上终结符'\0'的长度

//申请内存空间
result = (char *)malloc(length * sizeof(char));

//拷贝字符串
temp = result; //temp指向result
for (i=0; i<length; i++) {
*temp = *p; //按字符赋值
temp++;
p++;
}

return result;
}

void main()
{
char *str = "ABCDEFG";
char *result;
result = subString(str,-1); //调用函数
printf("%s\n",result);
}

用什么遍啊