标题: strcspn函数实现及简单应用 [打印本页]

作者: xiaojuan    时间: 2014-9-24 22:34
标题: strcspn函数实现及简单应用
//:Vc++6.0  String  strcspn函数
//功能:找到目标中第一个出现的字符
//参数:str1 字符串1  str2 字符串2
//返回值:返回该字符的下标
#include<stdio.h>

int strcspn(const char *str1, const char *str2);

int main()
{
char *str1 = "hello world 123";
char *str2 = "0123 ";

printf("%d\n", strcspn(str1, str2));

return 0;
}

int strcspn(const char *str1, const char *str2)
{
if (str1 == NULL || str2 == NULL)
{
perror("str1 or str2");
return -1;
}
const char *temp1 = str1;
const char *temp2 = str2;

while (*temp1 != '\0')
{
temp2 = str2; //将str2 指针从新指向在字符串的首地址
while (*temp2 != '\0')
{
if (*temp2 == *temp1)
return temp1 - str1;
else
temp2++;
}
temp1++;
}
return -1;
}

//在vc++6.0中的运行结果为:5
//注:在比较的时候空格也是在比较字符之内//:~






欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1