c++字符串查找函数实现

版权声明:未经博主允许,禁止转载 https://blog.csdn.net/Think88666/article/details/84311160
int find(const char*str,const char*sub_str) {
    //这里就没有判断指针是否是NULL了
    //保留起始地址以计算位置
    const char *temp_str = str;
    //默认返回结果
    int ret = -1;
    while (*temp_str != '\0') 
    {
    	const char *temp_str2 = temp_str;
    	const char* temp_sub = sub_str;    
	    while (*temp_str2&&*temp_str2==*temp_sub) {
	    	temp_str2++;
	    	temp_sub++;
	    }
	    //结束标志位
	    if (*temp_sub == '\0') {
	    	ret = temp_str - str;
	    	break;
	    }else
	    	temp_str++;
    }
    return ret;
}

猜你喜欢

转载自blog.csdn.net/Think88666/article/details/84311160