删除字符串中出现的特定字符:
char* del_char(char* str, char c)
{
int i = 0, j = 0;
while (str[i] != '\0')
{
if (str[i] != c)
{
str[j++] = str[i++];
}
else
{
i++;
}
}
str[j] = '\0';
return str;
}
strcpy源码:
char* strcpy_(const char* str, char* str2)
{
if (str==NULL&& str2==NULL)
{
throw "Invalid argument";
}
if (str == str2) return str2;
char* strdet = str2;
while ((*strdet++ = *str++) != '\0');
return strdet;
}
循环写成:
while (*strSrc != '\0')
*strDest++ = *strSrc++;
说明答题者对边界条件的检查不力。循环体结束后,strDest字符串的末尾没有正确地加上’\0’。
为什么要返回char *:
返回strDest的原始值使函数能够支持链式表达式,增加了函数的“附加值”。同样功能的函数,如果能合理地提高的可用性,自然就更加理想。
链式表达式的形式如:
int iLength=strlen(strcpy(strA,strB));
又如:
char * strA=strcpy(new char[10],strB);
strncpy
char *strncpy(char *strDes, const char *strSrc, unsigned int count)
{
if (strDes==NULL&& strDes==NULL)
{
throw "Invalid argument";
}
char *address = strDes;
while (count-- && *strSrc != '\0')
*strDes++ = *strSrc++;
*strDes = '\0';
return address;
}
strcmp
int strcmp(const char *s, const char *t)
{
assert(s != NULL && t != NULL);
while (*s && *t && *s == *t)
{
++ s;
++ t;
}
return (*s - *t);
}
strcat
char *strcat(char *strDes, const char *strSrc)
{
assert((strDes != NULL) && (strSrc != NULL));
char *address = strDes;
while (*strDes != '\0')
++ strDes;
while ((*strDes ++ = *strSrc ++) != '\0')
NULL;
return address;
}
strlen
int strlen(const char *str)
{
assert(str != NULL);
int len = 0;
while (*str ++ != '\0')
++ len;
return len;
}
strstr
char *Strstr(const char *strLong, const char *strShort)
{
char *cp = (char *)strLong; // cp是当前strShort的头在strLong中的位置
char *pL = NULL;
char *pS = NULL;
if ('\0' == *strShort)
return (char *)strLong;
while ('\0' != *cp)
{
pL = cp;
pS = (char *)strShort;
while ( ('\0' != *pL) && ('\0' != *pS) && (*pL == *pS) )
{
pL++;
pS++;
}
if ('\0' == *pS) // strShort比完了
return cp;
cp++; // 不匹配或strLong比完了而strShort还没比完
}
return NULL;
}
bool com(string &s1, string &s2) //string实现
{
auto it1 = s1.begin();
auto it2 = s2.begin();
//bool f = 0;
while (it1!= s1.end())
{
auto temp1 = it1;
auto temp2 = it2;
while (it1 != s1.end()&&*it1++== *it2++)
{
/*it1++;
it2++;*/
if (it2 == s2.end())
return 1;
}
it1 = ++temp1;
it2 = temp2;
}
return 0;
}
atoi
int StrToInt(string str)
{
if (str.size()==0)
{
return 0;
}
int ans = 0;
int temp = 1;
int flagminues = 1;
auto it = str.begin();
while (' '==*it)
{
it++;
}
if (*it=='+')
{
it++;
}
if (*it == '-')
{
flagminues = -1;
it++;
}
while (it!=str.end())
{
if (*it <= '9'&&*it >= '0')
{
ans = ans * 10 + (*it - '0');
it++;
}
else
return 0;
}
return ans*flagminues;
}