第一节、字符串查找
题目描述:给定一个字符串A,要求在A中查找一个子串B。
如A="ABCDF",要你在A中查找子串B=“CD”。
比较简单,相当于实现strstr库函数,参考代码如下:
int strstr(char *string, char *substring)
{
if (string == NULL || substring == NULL)
return -1;
int lenstr = strlen(string);
int lensub = strlen(substring);
if (lenstr < lensub)
return -1;
int i, j;
for ( i = 0; i < lenstr - lensub; ++i)
{
for (j = 0; j < lensub; ++j)
{
if (string[i + j] != substring[j])
break;
}
if (j == lensub)
return i;
}
return -1;
}
下面在贴出字符串复制的参考代码:
char *strcpy(char *strDes, const char *string)
{
if (string == NULL&&strDes == NULL)
return NULL;
char* address = strDes;
while (*string != '\0')
*(strDes++) = *(string++);
*strDes = '\0';//一定注意最后结束时一定要加一个\0结尾;
return address;//返回保存的strDes首地址;
}