접기
char *replaceAll(const char *s, const char *olds, const char *news)
{
if (NULL == s) return NULL;
char *result, *sr;
size_t i, count = 0;
size_t oldlen = strlen(olds);
if (oldlen < 1) {
return strdup(s);
}
size_t newlen = strlen(news);
if (newlen != oldlen) {
for (i = 0; s[i] != '\0';) {
if (memcmp(&s[i], olds, oldlen) == 0) count++, i += oldlen;
else i++;
}
} else
i = strlen(s);
result = (char *) malloc(i + 1 + count * (newlen - oldlen));
if (result == NULL) return NULL;
sr = result;
while (*s) {
if (memcmp(s, olds, oldlen) == 0) {
memcpy(sr, news, newlen);
sr += newlen;
s += oldlen;
} else *sr++ = *s++;
}
*sr = '\0';
return result;
}
char *replaceAll2(const char *s, const char *olds, const char *news)
{
if (NULL == s) return NULL;
char *result, *sr;
size_t i, count = 0;
size_t oldlen2 = strlen(olds);
if (oldlen2 < 1) {
return strdup(s);
}
size_t newlen = strlen(news);
int j;
for (i = 0; s[i] != '\0'; i++) {
for (j = 0; j < oldlen2; j++) {
if (news[j] == s[i])
count++;
}
}
result = (char *) malloc(i + 1 + count * (newlen - 1));
if (result == NULL) return NULL;
memset(result, 0, i + 1 + count * (newlen - 1));
sr = result;
short bFound=0;
while (*s) {
bFound = 0;
for (j = 0; j < oldlen2; j++) {
if (news[j] == *s) {
memcpy(sr, news, newlen);
sr += newlen;
s++;
bFound = 1;
break;
}
}
if (!bFound)
*sr++ = *s++;
}
*sr = '\0';
return result;
}
접기
진법 지정 인수가 있다.