#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
/*
2、有一个字符串”1a2b3d4z”,;
要求写一个函数实现如下功能,
功能1:把偶数位字符挑选出来,组成一个字符串1。valude;20分
功能2:把奇数位字符挑选出来,组成一个字符串2,valude 20
功能3:把字符串1和字符串2,通过函数参数,传送给main,并打印。
功能4:主函数能测试通过。
int getStr1Str2(char *souce, char *buf1, char *buf2);
*/
int getStr1Str2(char *souce, char *buf1, char *buf2)
{
char *p1=souce;
char *p2=buf1;
char *p3=buf2;
int i=0;
int j=1;
if(souce==NULL||buf1==NULL||buf2==NULL)
{
return -1;
}
while(*p1!='\0')
{
*p2++=p1[i];
*p3++=p1[j];
i=i+2;
j=j+2;
}
return 0;
}
int main ()
{
char buf01[]="1a2b3d4z";
char buf02[64]={0};
char buf03[64]={0};
getStr1Str2(buf01,buf02,buf03);
printf("%s\n",buf02);
printf("%s\n",buf03);
return 0;
}
#include <stdio.h>
/*
2、有一个字符串”1a2b3d4z”,;
要求写一个函数实现如下功能,
功能1:把偶数位字符挑选出来,组成一个字符串1。valude;20分
功能2:把奇数位字符挑选出来,组成一个字符串2,valude 20
功能3:把字符串1和字符串2,通过函数参数,传送给main,并打印。
功能4:主函数能测试通过。
int getStr1Str2(char *souce, char *buf1, char *buf2);
*/
int getStr1Str2(char *souce, char *buf1, char *buf2)
{
char *p1=souce;
char *p2=buf1;
char *p3=buf2;
if(souce==NULL||buf1==NULL||buf2==NULL)
{
return -1;
}
for (int i = 0; p1[i]; i++)
{
if (i % 2 == 0)
{
*p2 = p1[i];
p2++;
}
else
{
*p3 = p1[i];
p3++;
}
}
*p2 = *p3 = 0;
return 0;
}
int main ()
{
char buf01[]="1a2b3d4z";
char buf02[64]={0};
char buf03[64]={0};
getStr1Str2(buf01,buf02,buf03);
printf("%s\n",buf02);
printf("%s\n",buf03);
return 0;
}
可以啊 你俩个%s就好了啊
buf01的结尾不是'\0',getStr1Str2方法里的while执行完得到的结果并不是正确的。
#include <iostream>
#include <stdio.h>
using namespace std;
//从source 的第firstindex位置开始,每隔space个字符提取一个字符放到destStr
char* getStr(char* source,char* destStr,int firstindex=0,int space=2){
char *p1=source+firstindex;
char* mdest = destStr;
while(*p1 !='\0'){
*mdest++ = *p1;
for(int i=0;i<space;i++){
if(*(p1+i) == '\0'){
*mdest++ = '\0';
return mdest;
}
}
p1 += space;
}
*mdest++ = '\0';
return mdest;
}
int main()
{
char buf01[]="1a2b3d4z";
char buf02[64]={0};
char buf03[64]={0};
getStr(buf01,buf02,0,2);
getStr(buf01,buf03,1,2);
printf("%s\n",buf02);
printf("%s\n",buf03);
system("pause");
return 0;
}
测试过工具函数可以拿去直接用。你的代码最严重的的是while循环都没对p1递增,无限循环了。然后思路也不对,既然要用while循环了,却又用i,j+初始位来循环定位。