求教一道简单的题目
将字符串s2中的前m个字符存到字符数组s1中,并在结尾加上一个‘\0’。不能使用系统提供的strcpy函数。
2008-08-10 14:14
程序代码:/*******************************************************************************
将字符串s2中的前m个字符存到字符数组s1中,并在结尾加上一个‘\0’。
不能使用系统提供的strcpy函数。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
水平有限,谨作参考。
*******************************************************************************/
#include<stdio.h>
#include<string.h>
#define N 1000
int main(void)
{
char s1[N];
char s2[N];
int i,m;
printf("input s2[]:\n");
gets(s2);
printf("input m:\n");
scanf("%d",&m);
if(strlen(s2)>=m)
{
for(i=0;i<m;i++)
s1[i]=s2[i];
s1[m]='\0';
puts(s1);
}
else printf("S1数组没有足够的长度。\n");
return 0;
getch();
}
2008-08-10 16:57
2008-08-11 16:10
程序代码:/*用指针拷贝字符串*/
#include<stdio.h>
#include<windows.h>
void copy_string(char *str,char *result) //目的空间要事先分配好!
{
while(*str)
*result++=*str++;
*result='\0';
}
int main(void)
{
char *str="asddsfgdfgdgd";
char *res=(char *)malloc(1+strlen(str));
copy_string(str,res);
printf("%s\n",res);
return 0;
}
2008-08-11 17:07
程序代码:
/****************
*将字符串s2中的前m个字符存到字符数组s1中,并在结尾加上一个‘\0’。不能使用系统提供的strcpy函数。
*(仅仅提供思路,具体判断是否溢出可以自行加if判断)
****************/
#include <stdio.h>
#include <string.h>
using namespace std;
#define M 5;
int main(void)
{
char *pstr1, *pstr2;
gets(pstr2);
int i;
for(i=0;i<m;i++)
{
(*pstr1++)=(*pstr2++);
}
*pstr2+m='\0';
puts(pstr2);
return 0;
}
2008-08-11 19:39
2008-08-11 19:43
2008-08-11 19:55
2008-08-11 21:28
2008-08-12 09:37
2008-08-13 15:45