1 Star 0 Fork 1

guohuacai/learnC2

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
c语言实现将一个字符串的奇数位和偶数位分离并且分别保存.txt 2.28 KB
一键复制 编辑 原始数据 按行查看 历史
guohuacai 提交于 2021-01-29 07:20 . 学习总结
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
将一个字符串的奇数位和偶数位分别抽取出来保存到一个数组
*/
int getoddevent(char* src, char **odd, char **even)//这个需要传递指针的地址作为参数
{
//需要分配空间
*even = (char*)malloc(100);
*odd = (char*)malloc(100);
if (src == NULL||*odd==NULL||*even==NULL)
{
return -1;
}
int i = 0;
int count1 =0;
int count2 = 0;
int len = strlen(src);
//printf("src=%s\n", src);
char tem1[100];
char tem2[100];
for ( i = 0; i < len; i++)
{
if (i % 2 == 0){
tem1[count1] = src[i];
count1++;
}
else
{
tem2[count2] = src[i];
count2++;
}
}
tem1[count1] = 0;
tem2[count2] = 0;
//printf("even=%s,odd=%s\n", tem1, tem2);
strcpy(*even ,tem1);//在进行这一步之前,一定要注意*even必须指向一个合法内存单元
strcpy(*odd , tem2);
return 0;
}
int getoddevent2(char* src, char *odd, char *even)//这个需要传递数组作为参数
{
if (src == NULL || odd == NULL || even == NULL)
{
return -1;
}
char * tmp1 = odd;
char *tmp2 = even;
int i = 0;
int n1 = 0;
int n2 = 0;
int len = strlen(src);
for (i = 0; i < len; i++)
{
if (i % 2 == 0)
{
*tmp2 = src[i];
tmp2++;
n1++;
}
else
{
*tmp1 = src[i];
tmp1++;
n2++;
}
}
//printf("%s,%s\n", tmp1, tmp2);
even[n1] = 0;
odd[n2] = 0;
return 0;
}
int getoddevent3(char* src, char *odd, char *even)//这个需要传递数组作为参数
{
if (src == NULL || odd == NULL || even == NULL)
{
return -1;
}
int i = 0;
int len = strlen(src);
for (i = 0; i < len; i++)
{
if (i % 2 == 0)
{
*even = src[i];
even++;
}
else
{
*odd = src[i];
odd++;
}
}
//printf("%s,%s\n", tmp1, tmp2);
*even = 0;
*odd = 0;
return 0;
}
int main(int argc, char const *argv[])
{
char * p = "a1b2c3d4e5f6";
char *even;
char *odd;
getoddevent(p, &odd, &even);
printf("even=%s,odd=%s\n", even, odd);
printf("=================================================\n");
char even1[50];
char odd1[50];
getoddevent3(p, odd1, even1);
printf("even1=%s,odd1=%s\n", even1, odd1);
system("pause");
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guohuacai/learn-c2.git
git@gitee.com:guohuacai/learn-c2.git
guohuacai
learn-c2
learnC2
master

搜索帮助