標(biāo)題: strcspn函數(shù)實(shí)現(xiàn)及簡(jiǎn)單應(yīng)用 [打印本頁(yè)]

作者: xiaojuan    時(shí)間: 2014-9-24 22:34
標(biāo)題: strcspn函數(shù)實(shí)現(xiàn)及簡(jiǎn)單應(yīng)用
//:Vc++6.0  String  strcspn函數(shù)
//功能:找到目標(biāo)中第一個(gè)出現(xiàn)的字符
//參數(shù):str1 字符串1  str2 字符串2
//返回值:返回該字符的下標(biāo)
#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中的運(yùn)行結(jié)果為:5
//注:在比較的時(shí)候空格也是在比較字符之內(nèi)//:~






歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1