(指针与一维字符数组)分别用指针法写函数实现以下功能,并在主程序中进行测试。
(1) 写一个函数(自定义),它检查两个字符串是否由同一字符集组成,如abcc, bccca都由字符集{a, b, c}组成.
(2) 写一个函数(自定义),它判断一个字符串是否可以通过另一个字符串重排得到,如abcc和bcac可以通过对方重排得到。
思路分析:1.输入两个字符串 a,b
2.在(1)中,先将字符串计数(便于后续操作,也可用自带函数strlen),再将A组字符顺序排序,并消去重复字符(这里运用到相同即指针覆盖),即得到A组字符集;同理使用到B组中;再运用strcmp函数(需要<string.h>函数库),判断AB字符集是否相等,若相等,即有strcmp(A,B)=0判断依据。
3.在(2)中,直接将AB 两组字符顺序排序再用strcmp比较即可。
代码展示:
#include <stdio.h>
#include <string.h>
void test1(char*a,char*b);
void test2(char*a,char*b);
int main()
{
char arr[10];
char brr[10];
char* a = arr;
char* b = brr;
int i = 0;
int j = 0;
printf("请输入字符组A:");
scanf("%s",a);
printf("请输入字符组B:");
scanf("%s",b);
test1(a,b);
test2(a,b);
return 0;
}
void test1(char*a,char*b)
{
int i=0,j=0;//a数组长度,b数组长度
int n=0,m=0;
char temp;
while(*(a+i)!='\0')
{
i++;
}
while(*(b+j)!='\0')
{
j++;
}
//A:
for(int k=0;k<i;k++)
{
for(int u=0;u<i-k-1;u++)
if(*(a+u)>*(a+u+1))
{
temp=*(a+u);
*(a+u)=*(a+u+1);
*(a+u+1)=temp;
}
}
//覆盖重复
int q;
for(n=0;*(a+n);n++)
{
for(m=n+1;*(a+m);)
{
if(*(a+n) == *(a+m))
{
for(q=m;*(a+q);q++)
*(a+q) = *(a+q+1);
}
else
{
m++;
}
}
}
//B:
for(int k=0;k<i;k++)
{
for(int u=0;u<i-k-1;u++)
if(*(b+u)>*(b+u+1))
{
temp=*(b+u);
*(b+u)=*(b+u+1);
*(b+u+1)=temp;
}
}
for(n=0;*(b+n);n++)
{
for(m=n+1;*(b+m);)
{
if(*(b+n) == *(b+m))
{
for(q=m;*(b+q);q++)
*(b+q) = *(b+q+1);
}
else
{
m++;
}
}
}
if (strcmp(a, b) == 0)
{
printf("YES.They are made of the same. \n");
printf("Made from:{%s}",a);
}
else
printf("NO.They are not made of the same. \n");
}
void test2(char*a,char*b)
{
int i=0,j=0;//a数组长度,b数组长度
int n=0,m=0;
char temp;
while(*(a+i)!='\0')
{
i++;
}
while(*(b+j)!='\0')
{
j++;
}
for(int k=0;k<i;k++)
{
for(int u=0;u<i-k-1;u++)
if(*(a+u)>*(a+u+1))
{
temp=*(a+u);
*(a+u)=*(a+u+1);
*(a+u+1)=temp;
}
}
printf("\n");
for(int w=0;w<j;w++)
{
for(int t=0;t<j-w-1;t++)
if(*(b+t)>*(b+t+1))
{
temp=*(b+t);
*(b+t)=*(b+t+1);
*(b+t+1)=temp;
}
}
if (strcmp(a, b) == 0)
printf("A is equal to B \n");
else
printf("A is not equal to B \n");
}
代码运行结果:
代码小白,虚心求教,希望大佬指点!!