关于char型指针数组的问题
有没有哪儿位大佬能解释一下为什么当指针*s2跑完的时候while loop不会终止啊。代码/*
#include <stdio.h>
#include <assert.h>
#include <string.h>
int subset(char *s1, char *s2);
int main(int argc, char **argv) {
printf("is_subsequence(\"bee\", \"abbreviate\") = %d\n",
subset("bee", "abbreviate"));
printf("is_subsequence(\"bee\", \"brake\") = %d\n",
subset("bee", "brake"));
return 0;
}
intsubset(char *s1, char *s2) {
assert(s1);
assert(s2);
int i, length=strlen(s1);
while (*s2 && *s1) {
for (i=0;i<length;i++){
if (*s2==s1[i]){
s1++;
s2++;
break;
}
}
printf("s1=%s,s2=%c\n",s1,*s2);
s2++;
}
if (*s1){
return 0;
}
else {
return 1;
}
}
*/
printf测试结果
/*
s1=bee,s2=as1=ee,s2=bs1=ee,s2=rs1=e,s2=vs1=e,s2=is1=e,s2=as1=e,s2=ts1=,s2=is_subsequence("bee", "abbreviate") = 1s1=ee,s2=rs1=ee,s2=as1=ee,s2=ks1=e,s2=s1=e,s2=is1=e,s2=ss1=e,s2=_s1=e,s2=ss1=e,s2=us1=e,s2=bs1=e,s2=ss1=,s2=qis_subsequence("bee", "brake") = 1
*/
修改了你程序的几处错误,现在运行的结果与你的不同。由于不知道你这个程序是干啥的,没法再进一步了
#include <stdio.h>
#include <assert.h>
#include <string.h>
int subset(char *s1, char *s2);
int main(int argc, char **argv)
{
printf("is_subsequence(\"bee\", \"abbreviate\") = %d\n",
subset("bee", "abbreviate"));
printf("is_subsequence(\"bee\", \"brake\") = %d\n",
subset("bee", "brake"));
return 0;
}
intsubset(char *s1, char *s2)
{
int i,length;
assert(s1);
assert(s2);
length = strlen(s1);
while (*s2 && *s1)
{
for (i = 0;i < length;i++)
{
if (*s2==s1)
{
s1++;
s2++;
break;
}
}
printf("s1=%s,s2=%c\n",s1,*s2);
s2++;
}
if (*s1)
{
return 0;
}
else
{
return 1;
}
} 风过无痕1989 发表于 2020-10-14 16:50
修改了你程序的几处错误,现在运行的结果与你的不同。由于不知道你这个程序是干啥的,没法再进一步了
程序是来查找第一个字符串(*s1)里出现的字符是否在第二个字符串(*s2)里出现,其中第二个字符串中出现的相同字符的数量必须大于第一个字符串。如果出现返回1,没出现返回2。
比如说*s1=abc, *s2=cbaa, 返回1
*s1=aabc, *s2=cbba,返回0
int subset(char * s1,char * s2)
{
int nRet = 1;
int count_s1 = {0};
int count_s2 = {0};
if(strlen(s1) > strlen(s2))
{
return 0;
}
while(*s1 != 0)
{
unsigned char c = (unsigned char)*s1++;
count_s1++;
}
while(*s2 != 0)
{
unsigned char c = (unsigned char)*s2++;
count_s2++;
}
for(int i=0 ; i<256 ; i++)
{
if(count_s1 > count_s2)
{
nRet = 0;
break;
}
}
return nRet;
}
l94117312 发表于 2020-10-14 17:12
程序是来查找第一个字符串(*s1)里出现的字符是否在第二个字符串(*s2)里出现,其中第二个字符串中出现的 ...
你的S1、S2输入太复杂了,我没找到怎么输入,你自己试吧,程序我在VC++6.0 与 DEV_C++ 中编译都没有错误了 xieglt 发表于 2020-10-14 17:37
谢谢 风过无痕1989 发表于 2020-10-14 17:42
你的S1、S2输入太复杂了,我没找到怎么输入,你自己试吧,程序我在VC++6.0 与 DEV_C++ 中编译都没有错误 ...
好的好的,谢谢哥 l94117312 发表于 2020-10-14 18:28
好的好的,谢谢哥
像这种程序,最好是输入明确,别人看和自己将来回过头来再看,就能一目了然,像你现在这样隐藏在 printf() 函数之中,改哪个,真的很不容易 还没解决吗?帮你顶 l94117312 发表于 2020-10-14 18:28
好的好的,谢谢哥
如果满意了,回来选个最佳答案哈~~你这个举手之劳的动作不需要你付出任何(鱼币、荣誉值、积分),由系统给我们进行奖励:鱼币+3,荣誉+2,技术+1 没满意答案,帮你顶上去
页:
[1]